As an extension developer if you are submitting your code to Magento marketplace you must be familiar with code sniffer, Magento only accepts the extensions which are built on their coding standards, and to check the code whether it is following the standard or not we use code sniffer with Magento coding standard rules.
The code sniffer that Magento uses is Sqiz Lab’s code sniffer, which checks the code on some PHP code standards check such as PEAR coding standard or PSR, by default it uses PEAR coding standard or you can switch to any other standard by simply using this command:
$ phpcs --standard=PSR2 /path/to/code-directory
Magento uses its own code standard, which you can find on git:
It is quite a time taking to first build a module and test code standard and fix them, so it would be nice to add the coding standard check into the editor itself, so as you write code you can immediately fix the standard issues. Now we will see how we can add the Magento code standard check, in visual code studio editor or VS Code.
There is already a Sqiz labs code sniffer extension available for vs code so we just need to install that configure it to support Magento2 standard.
Open your visual code studio and press ctrl + shift + x it will open the Extensions tab like this:
Now search for ‘phpcs’ and you will get many results but I have installed Loannis Kappas extension, now click the green install button on the search item and code sniffer will get installed on your editor, now to configure magento2 standard first install the Magento coding standard library using composer on your system with this command:
$ composer create-project magento/magento-coding-standard --stability=dev InstallationDir
Using the above command Magento code standard will be installed in your system as a standalone software package. Now after installing code standard again open your vs code editor and press: ctrl + shift + p it will open the command pallet in that search for open settings and click on open settings in JSON, and add these two lines:
---- "phpcs.executablePath": "Path-To-InstallationDir/vendor/bin/phpcs", "phpcs.standard": "Path-To-InstallationDir/Magento2/ruleset.xml" ----
‘Path-To-InstallationDir’ will be your path to the Magento coding standard installation directory.
Now restart your editor and it will start showing code standard issues against Magento2 Code Standard on the fly, like below:
All the yellow underlined statements are code sniffer issues, when you will hover on then it will show you the issue description so that you can fix it.