Sunday, 19 November 2017

Installing Code Sniffer with Drupal Coding Standard on Windows

Below are the steps required for successful installation of PHP CoderSniffer with Drupal coding standard on Windows using gitbash.

1. Open you gitbash and check for composer path:
$ which composer
2. If you get composer not found or similar, follow Composer's installation instructions.

3. Install latest stable release of Coder Globally:$ composer global require drupal/coder

On Windows, the path may look like C:/Users/<WindowsUsername>/AppData/Roaming/Composer.

4. Below command will show you the installed location:$ composer global show -P

5. Make your coder version the preferred source:$ composer global update drupal/coder --prefer-source

6. On Windows, To have phpcs and phpcbf globally update your ~/.bashrc file to include:$ export PATH="$HOME/AppData/Roaming/Composer/vendor/bin:$PATH"

7. Install Drupal coding standard through plugin:$ composer global require dealerdirect/phpcodesniffer-composer-installer

8. Manually set installed path:$ phpcs --config-set installed_pathsC:/Users/<WindowsUsername>/AppData/Roaming/Composer/vendor/drupal/coder/coder_sniffer

9. Verify registered standard:$ phpcs -i

Now you should be able to use phpcs and phpcbf commands on your module files.

e.g. $ phpcs --standard=Drupal <my module path>/*

Auto correct coding standard issues found by the above command:

$ phpcbf --standard=Drupal <my module path>/*

Please remember that manually review your code after auto correction to avoid any unnecessary changes introduce by phpcbf itself.

Friday, 11 March 2016

Memcache with Drupal 7 on CentOS 7

Install Memcached

sudo yum -y install memcached

sudo vim /etc/sysconfig/memcached

Add check and alter below settings on it --

PORT=”11211″
USER=”memcached”
MAXCONN=”1024″
CACHESIZE=”64″
OPTIONS=”-l 127.0.0.1”

sudo systemctl enable memcached
sudo systemctl restart memcached

Install Memcached PHP Extension

There are two different extensions for it namely ‘memcache’ and ‘memcahed’. We are using memcahe here.

yum -y install php-pecl-memcache

Check memcached server

sudo yum -y install nc
watch "echo stats | nc 127.0.0.1 11211"

Check php extension (memcache)

php -m | grep -i "memcache"


Enable drupal memcache module

https://drupal.org/project/memcache

Then add the following to settings.php:

<?php
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
 $conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_key_prefix'] = 'unique_key';
?>

Put your site back in on-line mode and you’re done! Memcache also ships with memcache_admin module which you can enable to view the statistical reports on it. This is only used for development purpose.

Troubleshoot:

If you are facing issues to connect Memcache from your browser then give Memcache access to apache:

setsebool -P httpd_can_network_memcache 1


Tuesday, 8 March 2016

Steps for installing and configuring XHProf with Drupal 7 on CentOS 7

Execution time of each and every method involved in a single HTTP Request is the key factor for overall page load time and the process of collecting these information is called profiling.The two more popular extensions for this purpose are Derick Rethans‘ Xdebug and Facebook’s XHProf. Here we are focussing on XHProf only. 


Please follow the below steps to setup XHProf for Drupal 7 on your CentOS 7 environment with Apache.

Step 1:
Install plugin
            sudo yum --enablerepo=remi,remi-php55 install xhprof
This plugin is for loading graphical content
            sudo yum --enablerepo=remi,remi-php55 install php5-common graphviz

Step 2:
Enable the Xhprof module within php.ini file and specify the directory.
            extension=xhprof.so
            xhprof.output_dir="/tmp/xhprof"

Step 3:
Checking configuration files
cd /usr/share/xhprof/
Here, two folders xhprof_html and xhprof_lib should be available

Step 4:
Create a sym link to xhprof configuration files
sudo ln -s /usr/share/xhprof/xhprof_html/ xhprof

Step 5:
Virtual host configuration.
Open file --
vi vhosts.conf
Add entry --
<VirtualHost *:80>
        ServerAdmin vagrant@xyz.com
        DocumentRoot /var/www/html/xhprof
        ServerName xhprof.localhost
        Serveralias xhprof.xyz.com
        <Directory "/var/www/html/xhprof">
                #AllowOverride None
                AllowOverride All
                Require all granted
        </Directory>
</VirtualHost>

Open windows host file and add entry --
192.168.56.101 xhprof.xyz.com


Step 6:
Create a temporary directory.
cd /tmp
mkdir xhprof
chmod 777 /tmp/xhprof

Step 7:
Restarting PHP and httpd service.
            sudo systemctl restart php-fpm
            sudo systemctl restart httpd

Step 8: Enable Xhprof with Drupal 7 Devel module.
              drush dl devel
              drush en devel
drush vset devel_xhprof_enabled 1
drush vset devel_xhprof_directory "/usr/share/xhprof/"
drush vset devel_xhprof_url "http://xhprof.xyz.com/"

Step 9:
Clear drush cache and drupal cache
drush cache-clear drush
drush cache-clear all

Note:
Do not keep it (XHProf) enabled all the time. Before hitting the particular URL (for which you want to do profiling) on your browser enable it first. Once the page execution been completed then disable it immediately using below drush command.
To Enable : drush vset devel_xhprof_enabled 1

To Disable : drush vset devel_xhprof_enabled 0


If you feel it useful then please like it and share it, Thanks.

Thursday, 10 December 2015

PHPUnit Test : Write a Test Method Very Quickly For Your Actual Method!


I have written a single method 'testPhpUnit' inside Utility.php which will run 2 times through the data provider method 'providerTestPhpUnit'.

One will be succeeded and another will fail.

/**
 * @file
 * Unit tests (PHPUnit) to test your methods.
 */

/**
 * Class UnitTestUtilityValidate.
 */
class UnitTestUtilityValidate extends PHPUnit_Framework_TestCase {
/**
   * Test method.
   *
   * @param string $test_string
   *   The string to be tested.
   * @param string $expected_string
   *   The string we are expecting.
   *
   * @dataProvider providerTestPhpUnit
   */
  public function testPhpUnit($test_string, $expected_string) {
    $this->assertEquals($test_string, $expected_string);
  }
  /**
   * Data provider to testPhpUnit().
   *
   * @see testPhpUnit
   */
  public function providerTestPhpUnit() {
    
    $arr_csv_data[0][0] = xyz::actualMethodToBeTest('Hello');
    $arr_csv_data[0][1] = 'Hello';
    $arr_csv_data[1][0] = xyz::actualMethodToBeTest('Hello1');
    $arr_csv_data[1][1] = 'Hello2';
    return $arr_csv_data;
  }
}

/**
 * Class xyz.
 * 
 * Actual class where your actual method will be implemented.
 */
Class xyz {
  /**
   * Actual method to be tested.
   *
   * @param string $val
   *   The string we are testing.
   *
   * return string
   *   The output value that we need to test against the expected value.
   */
  public static function actualMethodToBeTest(string $val) {
    return $val;
  }
}


$ phpunit -c phpunit.xml --filter 'UnitTestUtilityValidate::testPhpUnit' UnitTestUtilityValidate /www/demodrupal/sites/all/modules/custom/utility/unit_tests/UnitTestUtilityValidate.php


Thursday, 27 March 2014

Installing and Configuring SonarQube for Drupal

Put your technical debt under control
SonarQube is an open source software quality management tool, dedicated to continuously analyze and measure source code quality. Using SonarQube throughout the whole development project life cycle drastically improves visibility for every stakeholder. This gained visibility allows to manage risks, reduce maintenance costs and improve agility by implementing a real quality first approach. Teams can now seamlessly embrace quality with fun.

Installing SonarQube
Download and unzip the SonarQube distribution 
wget http://dist.sonar.codehaus.org/sonarqube-4.0.zip -O /var/lib/sonar-4.0.zip
cd /var/lib/
unzip sonar-4.0.zip
mv sonarqube-4.0 sonar
cd /var/lib/sonar/conf/
vim sonar.properties
#----- Credentials
# Permissions to create tables and indexes must be granted to JDBC user.
# The schema must be created first. change this password according to your database password.
sonar.jdbc.username: sonar
sonar.jdbc.password: sonar
# Comment the embedded database and uncomment the following line to use MySQL
sonar.jdbc.url:
 jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
#----- Connection pool settings
sonar.jdbc.maxActive: 20
sonar.jdbc.maxIdle: 5
sonar.jdbc.minIdle: 2
sonar.jdbc.maxWait: 5000
sonar.jdbc.minEvictableIdleTimeMillis: 600000
sonar.jdbc.timeBetweenEvictionRunsMillis: 30000
# Delay (in seconds) between processing of notification queue
sonar.notifications.delay=60

Install Sonar PHP Plugin
cp sonar-php-plugin-0.2.jar /var/lib/sonar/extensions/plugins
Installing SonarQube Runner :
Follow the below steps for configuring SonarQube Runner to analyze your source code.
unzip sonar-runner-dist-2.3.zip
mv sonar-runner-2.3 /var/lib/sonar-runner/
vim sonar-runner.properties
#Configure here general information about the environment, such as SonarQube DB details for example
#No information about specific project should appear here
#----- Default SonarQube server
sonar.host.url=http://localhost:9000
#----- PostgreSQL
#sonar.jdbc.url=jdbc:postgresql://localhost/sonar
#----- MySQL
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8
#----- Oracle
#sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE
#----- Microsoft SQLServer
#sonar.jdbc.url=jdbc:jtds:sqlserver://localhost/sonar;SelectMethod=Cursor
#----- Global database settings
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
#----- Default source code encoding
sonar.sourceEncoding=UTF-8
#----- Security (when 'sonar.forceAuthentication' is set to 'true')
#sonar.login=admin
#sonar.password=admin
N.B. Default sonar web user/password : admin/admin

Link your project
Go to your project's root directory and add a new file with this name sonar-project.properties and add the below text and change according to your project. In my case project root directory is /var/www/myproject
# Required metadata
sonar.projectKey=myproject
sonar.projectName=My project
sonar.projectVersion=
1.0-SNAPSHOT
# Path to the parent source code directory.
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional. If not set, SonarQube starts looking for source code
# from the directory containing the sonar-project.properties file.
sonar.sources=profiles/myprofile
# The value of the property must be the key of the language.
sonar.language=php
# Encoding of the source code
sonar.sourceEncoding=UTF-8
# Additional parameters
sonar.my.property=value
After creating "sonar-project.properties" file run sonar-runner as shown below (make sure sonar is running) --
/var/lib/sonar-runner/bin/sonar-runner start -X
In case you are facing any issue then try with the below command --
/var/lib/sonar-runner/bin/sonar-runner -Dsonar.projectKey=myproject -Dsonar.projectName=MyProject -Dsonar.projectVersion=1.0-SNAPSHOT -Dsonar.sources=/var/www/myproject/profiles/myprofile -Dsonar.language=php -X
Start/Stop SonarQube
cd /var/lib/sonar/bin/linux-x86-64/
./sonar.sh stop
./sonar.sh start
Browse the results at http://<ip>:9000
N.B. SONAR is becoming SONARQUBE

Reference Pages


If this post is useful to you then please give a comments. Thanks.

Thursday, 15 November 2012

MVC or MVP ?

MVC and MVP both terms are correct but they have there own flavor. These are two different architectural pattern used in building a robust decoupled system in modern days. If you are building an application in a decoupled manner then definitely you will get following advantages --

1. It will decrease your maintenance cost.
2. Alteration and Modification will not hamper other modules thus making the developers life easy.
3. It will allow you to do parallel development and thus reducing the development time significantly.

and so on...

So basically MVC stands for Model View Controller and MVP stands for Model View Presenter.
The main difference between the two is how the manager (controller/presenter) sits in the overall architecture

MVC pattern puts the controller as the main ‘guy’ in charge for running the show. All application request comes through straight to the controller, and it will decide what to do with the request. One of the old patter used to achieve separation of concerns.

MVP (Supervising Controller) on the other hand, doesn't mind for the View to take on a bigger role. View is the first object instantiated in the execution pipeline, which then responsible for passing any events that happens on itself to the Presenter. Advanced form of MVC.




Individual responsibilities of each layers --

MVC : 

View:
1. Renders data
2. Receives events
3. Have basic validations
4. Can interact with Model directly

Controller:
1. Helps view in complex design making tasks
2. Communicate with model
3. Performs complex validation tasks

Model:
1. Communicate with Database Layer and send appropriate data to the requester (View/Controller)

MVP :

View: 
1. Renders data
2. Receives events
3. Have basic validations


Controller:
1. Helps view in complex design making tasks
2. Communicate with model
3. Performs complex validation tasks

Model:
1. Communicate with Database Layer and send appropriate data to the requester (Controller)



Interface


An interface has the following properties:
  • An interface is like an abstract base class: any non-abstract type that implements the interface must implement all its members.
  • An interface cannot be instantiated directly.
  • Interfaces can contain events, indexers, methods, and properties.
  • Interfaces contain no implementation of methods.
  • Classes and structs can implement more than one interface.
  • An interface itself can inherit from multiple interfaces.
     
Classes and structs implement interfaces in a manner similar to how classes inherit a base class or struct, with two exceptions:
  • A class or struct can implement more than one interface.
  • When a class or struct implements an interface, it receives only the method names and signatures, because the interface itself contains no implementations, as shown in the following example.
     
Example:
 
public class Car : IEquatable<Car>
{
    public string Make {get; set;}
    public string Model { get; set; }
    public string Year { get; set; }

    // Implementation of IEquatable<T> interface
    public bool Equals(Car car)
    {
        if (this.Make == car.Make &&
            this.Model == car.Model &&
            this.Year == car.Year)
        {
            return true;
        }
        else
            return false;
    }
}


The IEquatable(Of T) interface announces to the user of the object that the object can determine whether it is equal to other objects of the same type, and the user of the interface does not have to know how this is implemented.