Magento Coding Standard
Magento Coding Standard is a set of rules and sniffs for PHP_CodeSniffer tool. It is basically the official Magento Extension Quality Program Coding Standard with some additions and modifications I use., (*1)
It allows automatically check your code against some of the common Magento and PHP coding issues, like:
- raw SQL queries;
- SQL queries inside a loop;
- Direct class instantiation;
- Unnecessary collection loading;
- Excessive code complexity;
- Use of dangerous functions;
- Use of PHP super globals;
- Code style issues, (*2)
and many others., (*3)
Magento Coding Standard consists of two rulesets - Magento1 for Magento and Magento2 for Magento 2. Each of them contains the rules depending on the requirements of each version., (*4)
Usage
$ cd magento-coding-standard
Select the standard to run with PHP_CodeSniffer. To check Magento extension run:, (*5)
$ vendor/bin/phpcs /path/to/your/extension --standard=Magento1
To check Magento 2 extension run:, (*6)
$ vendor/bin/phpcs /path/to/your/extension --standard=Magento2
By default, PHP_CodeSniffer will check any file it finds with a .inc, .php, .js or .css extension. To check design templates you can specify --extensions=php,phtml option., (*7)
To check syntax with specific PHP version set paths to php binary dir:, (*8)
$ vendor/bin/phpcs --config-set php7.1_path /path/to/your/php7.1
$ vendor/bin/phpcs --config-set php7.0_path /path/to/your/php7
$ vendor/bin/phpcs --config-set php5.4_path /path/to/your/php5.4
Fixing Errors Automatically
PHP_CodeSniffer offers the PHP Code Beautifier and Fixer (phpcbf) tool. It can be used in place of phpcs to automatically generate and fix all fixable issues. We highly recommend run following command to fix as many sniff violations as possible:, (*9)
$ vendor/bin/phpcbf /path/to/your/extension --standard=Magento2
Dynamic Sniffs
Sniffs with complex logic, like Magento2.Classes.CollectionDependency and Magento2.SQL.CoreTablesModification require path to installed Magento 2 instance. You can specify it by running following command:, (*10)
$ vendor/bin/phpcs --config-set m2-path /path/to/magento2
Notice: Dynamic sniffs will not work without specified m2-path configuration option., (*11)
Notice: Don't forget to clear cache folder in project root directory if you want to run sniffs for other Magento versions., (*12)
Requirements
Notice: PHP and Composer should be accessible globally., (*13)
Contribution
Please feel free to contribute new sniffs or any fixes or improvements for the existing ones., (*14)