Dev & EngARTICLE

Standardizing your code with PHP CS Fixer

Gustavo Fraga presents PHP CS Fixer, a tool that applies the basic coding and code style standards to the PHP files in your project.

Standardizing your code with PHP CS Fixer
Image: Gustavo Fraga

Hey everyone! All good?

I'd like to write about a tool that I consider super important to have present in your PHP development stack.

I'm talking about the already well-known PHP Coding Standard Fixer, PHP CS Fixer.

About the tool:

The goal of PHP CS Fixer is to apply the basic coding and code style standards to the PHP files in your project.

It detects code that is out of standard and applies a “fix”, turning these occurrences into code that follows the language's current coding recommendations defined by PHP-FIG.

Installation:

bash
composer require --dev friendsofphp/php-cs-fixer

Using the tool

Consider the script below:

In it we find some passages that don't comply with the standards defined in PSR 1 and PSR 2. Among them:

  • 1. Always include a blank line between the namespace declaration and the “use” declarations
  • 2. Never use the word “var”, and always declare visibility for properties
  • 3. Always declare visibility for methods
  • 4. The “final” must precede the visibility declaration. There is no space between the method name and the opening parenthesis, and the opening brace must be positioned on the next line with the proper indentation

These are just some examples of “violations” of the current recommendations that can be fixed by the tool.

Now, shall we fix it?

To do this, just run the command below, pointing to the file/directory you want to affect:

bash
php vendor/bin/php-cs-fixer fix PdfGenerator.php

Result:

As we can see, all the writing inconsistencies were detected and resolved very quickly and efficiently!

Notes:

By default, PHP CS Fixer applies PSR 1 and PSR 2 in its detections, but we can define custom rules, appending them directly in the command or in a configuration file.

To see all the details, coverage and possibilities for using the tool, I strongly recommend visiting the project's page through this link.

Conclusion

Without a doubt, PHP Coding Standard Fixer is an excellent support tool for PHP devs, performing the detection and correction of code that falls outside the standards recommended by the community and, thus, contributing to the development of maintainable projects.

I hope this article has been useful to you.

Big hug!

Translated from the Brazilian Portuguese original · Read the original