10 June 2022
PHP static code analysis – keep your code under control
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, given enough 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 with some tools, which can help you keep your PHP code clean. The time has come to brush up on static code analysis in PHP!
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 a 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?
PHP static code analysis is an action performed by a static code analysis tool, designed to read the PHP source code without actually running it. Performing such an analysis is usually a part of the Continuous Integration process. Static analyzers allow programmers bounding and predicting the behavior of software without running it.
The static code analyzer also simplifies and helps 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:
- Easy Coding Standard (ECS),
- PHPStan,
- Psalm.
More on those three later. In addition to them, there are also a lot of other tools. In my personal experience, I only used them sparingly, but some of them are definitely viable. You’re welcome to give them a try.
- PHP Code Style Fixer (PHP CS Fixer)
You can fix your code according to a chosen standard, including those developed by specific communities such as Symfony.
- PHP Code Sniffer (PHP_CodeSniffer)
Corrects coding standard violations and tokenizes PHP, JS, and CSS files
A code analyzer with the goal of proving incorrectness, avoiding false-positives.
Works with many frameworks, provides pretty reports.
It can help you upgrade your PHP.
This one has a large community and supports a lot of languages besides PHP.
It describes itself as a tool that helps visualize and enforce architectural decisions. Still in development.
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: the aforementioned ECS, PHPStan, and Psalm.
WhyECS, PHPStan, and Psalm 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
With that said and done, we can proceed towards checking out the tools.
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
- Run the checker:
vendor/bin/ecs check src
(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 for PHP static code analysis?
Now, the code looks much cleaner! With a PHP static analysis tool, you can:
- improve code quality by making it more readable and efficient,
- spot and resolve all kinds of problems, including security vulnerabilities.
But wait, isn’t your brain satiated with this knowledge? Do you ask yourself questions: “Why are there so many of these PHP static code analysis 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 PHP code still needs a proper static code analysis?
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 fill in the contact form.