Configure PHPCSF (PHP CodeSniffer Fixer) for Magento

In the previous lesson, we discussed the PHP Code Sniffer, a tool that notifies us when our code isn't in compliance with Magento's standards. However, there is another tool, the PHP Code Sniffer Fixer, which automatically rectifies these issues.

Setting up PHP Code Sniffer Fixer

To set this up, navigate to your PhpStorm Settings. Expand PHP and Quality Tools sections. We should already have PHP Code Sniffer set up, so we're now going to focus on PHP CS Fixer.

The configuration process for PHP CS Fixer mirrors what we did for PHP CS. Click on the triple dot icon to initiate the setup of a configuration. Next, click the '+' sign and select our PHP FPM interpreter, which is housed within our Docker container.

Remember to ensure the PHP CS Fixer path is directed to /var/www/html/vendor/bin/php-cs-fixer. Then click 'Validate'. A version should appear, confirming that PHP CS Fixer has been successfully installed.

Our path mappings should already be configured from our initial PHP Docker setup. Click 'OK' to continue.

Defining Ruleset for PHP CS Fixer

The next step involves defining a ruleset. Click the folder icon to continue.

Navigate to the src directory and select any file. The custom ruleset that Magento provides is actually a hidden file, so we'll need to manually type its location: .php-cs-fixer.dist.php. This will replace the file previously selected.

After entering the location, toggle on the configuration and click 'OK'.

How PHP CS Fixer Works

With PHP CS Fixer enabled, when we encounter a code snippet that needs correcting, PHP CSF will automatically fix it. For instance, if we add an extra space and hover over the squiggly line that appears, we'll see an error indicating incorrect indentation. Clicking the 'fix the whole file' link will automatically correct this indentation.

However, we don't want to manually hover over each squiggly line whenever a correction is needed. Thankfully, PhpStorm can handle this for us automatically.

Automating PHP CS Fixer in PhpStorm

To automate this process, navigate to PhpStorm Settings again, scroll down to 'Tools' and expand the section. Here, find 'Actions On Save'. The first item is 'reformat code'. Check this option and click 'OK'.

Now, whenever we have something indented improperly, all we need to do is save the file, and PHP CSF will automatically rectify it. This feature is particularly beneficial as it ensures you'll never have to worry about improper indentation, syntax, or any other code issues again.

Complete and Continue