PHP Code Sniffer
Nowadays there are many tools that help developers to keep code clean and consistent. PHP Code Sniffer is one of such tools, which allows automatically detect violations of a defined set of coding standards.
Each Magento 2 project has preinstalled PHP Code Sniffer and set of rules and sniffs for this tool.
To define PHP Code Sniffer for Magento 2 project in PHPStorm IDE, follow next steps:
Open PHPStorm IDE
Open PHPStorm IDE and go to Settings > Languages & Frameworks > PHP > Code Sniffer and set PHP Code Sniffer (phpcs) path. In Magento 2 project it will be:
Go to the Settings > Editor
Go to the Settings > Editor / Inspections / PHP / PHP Code Sniffer validation and select Custom Coding Standart.
Enter Root directory
Enter Root directory of Custom Coding Standart:
Change settings for code scope validation
We can change settings of code scope validation, go to Code > Inspect Code:
Result of validation
For custom extensions, developers should use Magento Extension Quality Program Coding Standard. This is a set of rules and sniffs for PHP Code Sniffer, that 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 superglobals;
- code style issues.
To use Magento EQP Coding Standard, follow next steps:
1. Install Magento EQP via composer:
composer create-project --repository=https://repo.magento.com
magento/marketplace-eqp magento-coding-standard && cd
2. Use it by running next commands:
For Magento 1.x
vendor/bin/phpcs /path/to/your/extension --standard=MEQP1
For Magento 2.x
vendor/bin/phpcs /path/to/your/extension --standard=MEQP2
3. The result of validation:
Read also the official documentation: