How many times have you seen a code that seemed to be written in a rush? Multiple times, I believe. In some cases, it’s written by someone else, but pretty often your own creations, after some time, make you think “who the hell wrote this crap”? Keeping code clean ain’t easy and that’s why I’ve decided to present you some tools which can help you keep your PHP code clean.

Keeping code under control is one thing, but even worse is the fact that there are no universal standards of coding. Huge, open-source projects, frameworks and libraries apply their own programming standards. The problem has been noticed some time ago, and it led to the origins of PHP Standards Recommendations (PSR). It’s the document made jointly by the authors of the most popular PHP projects.

Even though the key recommendations (PSR-0 to PSR-4) have been acknowledged by the majority of the PHP community as a de facto standard, later attempts at unifying more common application elements often failed and so many people have left the project since, including the authors of such famous projects as Symfony, Laravel, Doctrine or Guzzle.

Developers also vary their standards of code quality and cleanliness. The lack of coding standards sanitization at the project level can lead to needless disputes during the Code Review.

Maintaining a fairly good code quality isn’t an easy task. Below, I’ll try to show you a few static code analysis tools, which might help you with that.

But what is static code analysis?

It’s an action performed by tools designed to read the source code without actually running it. Performing such an analysis is usually a part of the Continuous Integration process. Static analysers allow programmers bounding and predicting the behavior of software without running it. They also simplify and help reviewers checking the code, according to the rule “what can be automated, should be automated”.

The variety of static code analysis tools in the PHP community is quite huge. Some of those are:

PHP Code Style Fixer (PHP CS Fixer),

PHP Code Sniffer (PHP_CodeSniffer),

Easy Coding Standard (ECS),

PHPStan,

Psalm,

Phan,

PHP Insights,

Rector.

In the next part of the article, I’ll present you three of my favourite code analysers, which I use in most of my projects: ECS, PHPStan, and Psalm. Why those in particular? Among many options those are the ones which are, in my opinion, the easiest to use and provide the most advantages. Why three and not just one? Because those tools complement each other.

As I mentioned earlier, projects often have different, “stale” code writing styles. Programmers involved in the project also have their own habits. That’s why the configuration of the analysers has to be individualized for each project and should be saved in the repository of that project. To facilitate the configuration process, I’ll show you some elementary configuration files we use at The Software House.

Fix my code!

Before you start fixing your code, it’s worth learning a few rules, which can help you along the way.

Commit the code before you run any command that changes the code and before making any changes in the configuration of the tool. Running it may result in the script ruining your code and the changes can be difficult to recover. Run tests after each code change to be sure that everything still works as expected. When configuring an analyser, it’s best to start with all available checkers and fixers. Then, you should exclude those you do not need or want to be executed. After all, you’ll end up with the highest fitting number of enhancements. It’s pointless to use IDE plugins for this task or even to add those scripts as pre-commit hooks. Using them distracts the programmer . Instead, it’s better to run the checks just before pushing your code to the repository and, crucially, in CI. If your code is very old, conflicts in Composer’s dependencies can arise. In such a case, the solution would be to install those tools in a separate directory, for example under ./ecs/composer.json

EasyCodingStandard – one tool to rule ‘em all!

ECS is a static code analyser made by Tomas Votruba and contributors. It’s able to fix most of your code flaws automatically. It contains rules from PHP Code Fixer, Code Sniffer, Slevomat and Simplify. Also, it greatly simplifies the configuration of thereof. Sounds too good to be true? Check it for yourself!



Below, there is an exemplary ECS config which I use (with some customization) in most of my projects.

Alright, but you may ask “how to use it?” Below, you’ll find a few simple steps:

Save the above code in the main project folder (in ecs.yaml file). Install ECS: composer require --dev symplify/easy-coding-standard vendor/bin/ecs check src (the command executes dry-run by default – it means that it checks the code, but won’t change it).

Run the checker:(the command executes dry-run by default – it means that it checks the code, but won’t change it). Check the proposed changes. If any of them don’t meet your requirements, delete the respective rules from the configuration file or add them to the “skip” section. You can also add exceptions to specific files here and return to step 3. After reaching a satisfying result, let the program fix your code. For this purpose, commit the changes and then execute the command from step 3. This time, you should do it around with the “fix” argument: vendor/bin/ecs check src --fix Not everything can be fixed automatically. If something is left in output, modify the code manually until the command’s output becomes green. Execute the test and/or click through the application to check if it still works properly. If something went wrong during the process, you can revert the code state to the commit you made before the fix command. Done. 🙂

Doing this may greatly improve your code’s quality. But hey, we are not done yet! Let’s see what else you can improve by using some more tools.

PHPStan

PHPStan is another useful tool. Its configuration is simplified to the bare minimum – you choose one of the predefined levels. In addition to that, you can expand its capabilities using one of many extensions. The downside is that this analyser doesn’t have an automatic code fixing function. Here is an exemplary config:

Again, let’s answer the question: how to use it?

Save the above code in the project’s main directory, in the phpstan.neon file. Install PHPStan: composer require --dev phpstan/phpstan Launch it: vendor/bin/phpstan analyse src Fix errors presented in the output. Execute tests and/or click through the application to check if it still works properly. Now, you can raise the level in configuration and then go back to step 3, up until you reach a satisfying effect. From my experience, most projects will stop at levels 3 to 5. Done. 🙂

Psalm

The last of the tools which I use on a daily basis is called Psalm. It was made by Vimeo. Unfortunately, just like PHPStan, your code won’t be fixed automatically. The configuration is done through an XML file and offers a lot of capabilities. My recommendation would be to begin with all the rules at the minimum level of “warning”, gradually excluding them. The final config would look like this.

How to use it?

Save the above code in the project’s main directory, in the psalm.xml file. Install Psalm: composer require --dev vimeo/psalm Launch it: vendor/bin/psalm --show-info=false If there are too many errors or you don’t agree with any of them, you should exclude the rules and files which you aren’t going to correct. Fix your code accordingly to the remaining rules. Execute the test and/or click through the application to check if it still works properly. Done. 🙂

If you are interested in seeing some real examples of the aforementioned tools, I’ll recommend you visiting our working example of those analysers on GitHub repository.

What’s next?

Now, the code looks much cleaner! But wait, isn’t your brain satiated with this knowledge? Do you ask yourself questions: “Why are there so many of these tools? Why isn’t it enough to just use one of them? What ways do they differ in”?

If so, then I’d like to recommend you some more detailed technical articles on the excellent blog made by Tomas Votruba, the creator of the aforementioned ECS, which will hopefully answer those questions:

Don’t feel like reading them but your code still needs a proper clean up? At The Software House, we have a team of very dedicated PHP developers who will gladly keep your code style under control. In order to receive a free consultation, all you need to do is filling in the contact form.