PHPStan – must-have tool for PHP Developer

PHPStan is a tool that allows for automatic static analysis of the source code. The tool is very easy to install and configure: just select the application directory that you want to analyze, indicate the level of analysis of the code to be executed and after a while we get a detailed report on potential errors in our code. If you still do not use static code analysis in your projects, this is the best moment and tool you should start with.

What is static code analysis?

Static code analysis is a code test for syntax errors, coding standards and other common errors (depending on configuration) without running the real code. In the case of PHP this is useful because we do not have a source code compiler and errors in the code that are not properly covered by automatic tests are very difficult to detect – in extreme cases they are detected / reported only by end users.

Choose the right level of analysis for your project

Depending on the type of project we want to analyze, we should first select the appropriate “level” of the code analysis. The higher level the more errors PHPStan will report to us. In this situation it is good to start with the default level: 0 and fix all detected issues. In the next steps, we can increase the level of code analysis. An interesting solution is the ability to configure PHPStan startup as pre commit hook , thanks to this the analysis will be run automatically before each commit and will not allow you to send changes that contain errors. PHPStan also works great as a CI (Continuous Integration) element.

PHPStan vs unit tests

Static code analysis can not and should not be treated as a substitute for unit tests. This type of code analysis helps to detect errors at the early programming stage and helps to maintain the right quality because even a well-tested code may contain errors. Each newly generated line of code generates potential bugs, that’s why additional help in the form of quick code analysis without necessarily executing the code is so important. What’s more, PHPStan will also be very useful in projects that do not have any tests, but you should definitely avoid such situations.

It is worth mentioning that PHPStan also offers the possibility of configuring useful extensions for better code analysis of PHPUnit , Doctrine2 , Symfony or Laravel .

The project is very intensively developed. The latest version requires at least PHP 7.1 but earlier versions that support e.g. PHP 7.0 are also available. I encourage you to familiarize yourself with this tool. The official project repository: https://github.com/phpstan/phpstan .

Rate this post