Configure PHPCS (PHP CodeSniffer) for Magento
PHP Code Sniffer is a tool that can examine your code and apply a rule set to it, notifying you if any part of your code does not comply with the established rules. This can be a powerful aid in achieving consistent, high-quality code over time.
Configuring PhpStorm Settings
To set up PHP Code Sniffer, navigate to your PhpStorm settings. From there, expand the PHP option and then further expand the quality tools option. This will allow you to click on PHP Code Sniffer.
Before using PHP Code Sniffer, you need to define a specific binary. This can be done by clicking on the triple dot icon.
Setting Up PHP Interpreter
Since PHP runs within our Docker container, we cannot use the system PHP which is the localhost PHP. Instead, click on the plus sign and assign the interpreter that was set up previously. The PHP FPM assigned to Docker should be used. After doing so, click OK.
Specifying Code Sniffer Path
For the Code Sniffer path, specify the path that is within the Docker container since we are using the PHP binary within the container. Type /var/www/html/vendor/bin/phpcs
. After typing this, click Validate to confirm that the correct version has been found.
Setting Up PHP Code Beautifier
While you're in the settings, also set up the PHP Code Beautifier. This is located in the same place as the "phpcs" binary, but is named "phpcbf". So this location would be /var/www/html/vendor/bin/phpcbf
.
Restart and Apply Updates
After clicking OK and returning back to the settings, you can enable PHP Code Sniffer. You will then need to close the PhpStorm Settings dialog, and then reopen it to see a new set of coding standards.
There will now be a new coding standard that displays, name Magento 2. Select Magento 2 and also toggle on "Show sniff name". This will be helpful as it lets you know which rule or "sniff" is being triggered by your code. Click OK to save these changes.
Testing PHP Code Sniffer
To test if your PHP Code Sniffer setup is working, create some code. For this example, create a sample module and the related registration.php file. Populate this with code that you know will trigger an error, such as:
$base = basename($_SERVER['SCRIPT_FILENAME']);
When the error is triggered, you will see a yellow squiggly line and a notification from phpcs. This indicates that PHP Code Sniffer is set up correctly and can now validate your Magento code.