I am creating a custom extension for Magento 2 and looking for the tool that can help me in the code standards. I come to know about PHP code sniffers from google.
Is the PHP code sniffer is right tool for Magento coding standard? or We have some other tools?
Best Answer
For those, who come here from the google some instructions about how to install and use this great tool with PHPStorm:
You should install PHP_Codesniffer. The simplest way is to require it using your composer (but you can read about another way on the code-sniffer page):
Then you should detect, where is
phpcs
. If you install it usingcomposer global require
you can detect absolute path using command:As a result you can see the path from root, for me it looks like this: so my
phpcs
accessible by path/Users/sergei/.composer/vendor/bin/phpcs
and when I type/Users/sergei/.composer/vendor/bin/phpcs -h
in the console I see thephpcs
help message: This message means that code-sniffer was installed successfully and can be used to make the code better.Install the Magento coding standards. All standards stored in the code-sniffer
CodeSniffer/Standards
directory. If you install it like in my example, it can be found in the global composer directory invendor/squizlabs/php_codesniffer/CodeSniffer/Standards/
for me this path from root was/Users/sergei/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/
. We should download MEQP1/MEQP2 manually and copy it to the standards directory:cd ~
)git clone git@github.com:magento/marketplace-eqp.git
(or download it manually using your web-browser)Do checkout to the version
1.0.5
of the standardsCopy the standards and Utils to the Squizlabs code-sniffer standards directory:
Now you are able to use the code-sniffer with Magento standards from the command line like this:
where the path
/Users/sergei/PhpstormProjects/aws-botapi/app/code/MageWorx/ShippingRules
should be a path to the directory with your code.Add code-sniffer to the PHPStorm to make access to it simplest. Open PHPStorm. Open the
Preferences > Tools > External Tools
:and click on the
+
, then add next info:phpcs
, in my example it was/Users/sergei/.composer/vendor/bin/phpcs
$FileDir$ --standard=MEQP1
. Note that the$FileDir$
is a variable in the PHPStorm which means a currently selected file or directory.$ProjectFileDir$
varaible (by default)Now it can be accessible from the External tools from context menu right in the PHPStorm:
Just select desired directory or file, right-click on it and select External tools > MEQP1 and you can see a result of this test in the bottom of working space (the
Run
tab):You can add MEQP2 test the same way (using the
+
button or theclone
button), just add another name, likeMEQP2
and change the standard in the arguments input:PS: we use the version of standards
1.0.5
andphpcs
of version 2.6.2 because its compatible and works good, when version of the standards from the master does not work :(