December 11th, 2024, posted in for_founders
by Adelina
What's the first thing that comes to your mind when you think of “software testing”? Is it QA engineers writing test cases? Or the QA team checking if the software works properly and meets specifications? If your answer is either one, you might be missing out on one of the most underrated tools for maintaining quality under pressure: static code analysis.
As a PHP Laravel developer, there are a lot of great static analysis tools you can use. Especially if you work on large projects with tight deadlines and a lot of code that needs to be reviewed daily. In this article you`ll find some of our top choices, tools we regularly use in all our Laravel projects.
What is static code analysis?
Static code analysis is a way to test the quality of your code and find bugs or inconsistencies without actually running the code (hence “static”). It's usually performed before you “test” the application in the traditional sense of the word. This ensures that the code you pass on to the QA team is the highest quality possible. Static analysis tools allow you to grade code performance, check it against coding standards or discover things like unused variables and deprecated functions.
The code reviewer that never sleeps
In software development, feedback can sometimes be frustratingly slow. Let's say you're unable to run the tests locally, so you need to push your code to GitHub, want several minutes for the checks to run and then the test fails. The biggest advantage of static analysis is that it provides an automated feedback loop. You fire up the analysis tool, it goes over your code and reports back any issues almost instantly. Instant feedback equals quicker fixes, quicker fixes equal less time-consuming issues down the road.
Static analysis tools also provide an additional layer of protection. Think of it as a code reviewer that never sleeps. They can catch errors that are tricky to spot for humans or issues that might be overlooked when writing test cases or running dynamic tests. Things that are not necessarily complex, but tend to be overlooked precisely because they are common and would require some serious nitpicking by a human code reviewer. In our experience working with PHP Laravel, here are a few:
- unused elements (unused variables, private elements, parameters etc.)
- empty statements
- incorrect indentation (array indent, object operator indent, method chaining etc.)
- incorrect use of whitespace
- inconsistent uppercase, lowercase use
- inconsistent or superfluous naming conventions
Our top static analysis tools for PHP Laravel
These are some of the tools we use to keep our Laravel code clean and easy to maintain. For most of these tools, you can either use the default coding standard shipped with them or implement your own rules. Since you can start with almost no configuration, it's easy to integrate them in your workflow. As you get accustomed to them, you can write new rules and tailor them to your needs.
You can use these tools in your local environment or hook them up to your CI/CD pipelines to automate the process and enforce the same quality standards across the team.
1.) Laravel Pint
Laravel Pint is one of the recent linting tools in the Laravel ecosystem (its name is in fact a contraction of “PHP” and “lint”). Linting tools analyze your code against a coding standard (PSR-12 is the current standard for PHP) and then apply formatting and style fixes to make it more readable and consistent with those standards.
Pint is automatically installed with all new Laravel applications, so you can use it out of the box. However, since it's a relatively new addition to the Laravel ecosystem, you might need to install it via Composer if you are working on an older application. You can use Pint for any PHP project, not just Laravel, and for other standards in addition to PSR-12.
By default, Pint uses the laravel preset. This means it fixes code style issues using the opinionated coding style of Laravel, but you can change that by setting a different preset. Pint also supports PSR-12 and Symfony presets. You may specify a different preset by providing the --preset
option to Pint:
pint --preset psr12
Here is an example of Pint in action. You can notice in the output how Pint easily tracks and fixes misplaced, misaligned or altogether missing braces. This not only makes the code cleaner and easier to read, but it also ensures your code respects the PSR-12 standard. A bad indentation or missing brace can happen to anyone and tools like Pint are great at finding and fixing common style and formatting issues.
Laravel Pint is built on top of PHP-CS-Fixer. Therefore, you can use any of the PHP-CS-Fixer rules to configure Pint. You can use these rules to fix anything from misplaced braces, like in the example above, to array indentation or unnecessary whitespace. You can see a full list of the rules you can use to create your own configuration here. For the official Laravel Pint documentation, you can check out their website.
2.) PHP Code Sniffer (PHPCS)
Similar to Pint, we use PHPCS to make sure all our code complies to the PSR-12 standard. Because they enforce a standard coding style, tools like Pint and PHPCS make code review less time consuming for the entire team and keeps everyone on the same page. We like to think of code style fixers as our number one collaboration tool, right after our Discord channel.
PHPCS comes with a few built-in presets, other than the Laravel, Symfony and PSR-12 ones provided by Pint. Out of the box, PHPCS comes with the following standards: PEAR, PSR-1, PSR-2, Squiz and Zend (you can run phpcs -i
to see all available standards). From syntax checking to whitespace and naming conventions, PHPCS can analyze your code and highlight any coding standard violations.
You can run phpcs
to output the coding standard violations.
Additionally, you can use phpcbf
to automatically fix some of the errors.
You can check out the PHPCS wiki for a complete list of rules and commands.
3.) PHP Insights
Pint and PHPCS are great for fixing style issues and standard violations. But sometimes you need a quick way to understand what's happening in the entire codebase. Get the big picture in terms of complexity, architecture, style and overall code performance. For this purpose, we use a scoring tool called PHP Insights.
PHP Insights is a static analysis tool which can give you an overview of your codebase by providing performance scores in 4 categories. It's a useful tool to get quick feedback and see if you`re moving in the right direction by comparing scores before and after refactoring.
After running Insights, you will get a score in each of these categories:
code: it provides insights regarding your use of classes, comments, functions and globals.
complexity: analyzes cyclomatic complexity, which is another way to say how much your statements branch out. One point is added for every “case,” “for,” “if,” and “while”. The goal is to keep your complexity score as low as possible - the lower the score, the easier your code is to read and understand.
architecture: it looks at things like naming conventions and the length of functions or classes.
style: behaves similarly to a linting tool like Pint, but it also provides a style score and can spot a few additional things such as line counts.
To use Insights, simply type in:
phpinsights analyse ./src
An Artisan command is also provided to run PHP Insights, if you`re working on a Laravel project.
php artisan insights
This will show you how well your codebase is performing in each category.
Insights also allows you to automatically fix some of the found issues. You can launch fixes using the fix command:
php artisan insights path/to/analyse --fix
Last but not least, by using the –summary
option, you can get real-time monitoring while you code. Basically, everything you type in on the left-hand side is automatically analyzed in the right-hand side panel and the score gets updated. A cool way to see the state of your code in progress.
PHP Insights comes with a lot of rules you can use to configure it. For a full list, you can check the official documentation here. Our developers like to call Insights the Solid Checker, not only because it enforces SOLID principles, but also because it does a solid job keeping our codebase clean.
4.) PHPStan
PHPStan is another tool we use to keep code bugfree and remove any errors at runtime. For example, PHPStan can look at something like a string variable used with a function as an array argument and catch it on time, without having to run the code.
To have PHPStan analyze your codebase you can use the “analyze” command and point it to the directories of your choice.
vendor/bin/phpstan analyse src tests
Here is a basic PHPStan configuration we use.
By default, PHPStan runs basic checks, but you can tweak its Rule Levels to make the checks more strict. PHPStan allows you to choose from 10 levels, with 0 being the loosest and 9 the strictest. For example, a level 0 check will only look at things like unknown classes, functions, and methods or the wrong number of arguments passed to those methods and functions. In comparison, stricter checks will look at missing typehints, calling methods and accessing properties on nullable types and so on. You can check out the documentation for the complete list of Rule Levels.
To specify the desired level, simply add -l|--level
to the “analyze” command.
If you`re working with Laravel, be sure to also check out Larastan. It has a set of PHPStan rules that work well for Laravel and it understands Laravel models with dynamic attributes and scopes better.
Bonus - Sonarqube
If you`re looking for a fully automated solution, you can also look into integrating Sonarqube into your CI pipeline and DevOps platform. Similar to PHP Insights, it also provides a summary report. Discovered issues can either be a Bug, Vulnerability, Code Smell, Coverage or Duplication. Each category has a corresponding number of issues or a percentage value. If it`s well configured, you can use it to keep track of all the company's projects and development activities, so it also doubles as a management tool.
Summary
If you`re not already using them, static analysis tools are a game-changer when it comes to keeping your codebase clean and maintainable. They`re a great way to catch and fix common issues, while letting the human code reviewers focus on the really tricky parts. All in all, they`re a great way to automate and speed up the code review process and to set a code quality standard across the entire team.
Want to build a strong app with a clean codebase? Contact us
If you`re looking for the best Laravel developers, make sure to also check out this listing where UPDIVISION is featured among the top Laravel development companies.