Static Code Analysis for Laravel

Wednesday, February 17, 2021 • 7 minutes to read

Today I will show you what type of static code analysis tools I use for Laravel based projects. All of them, with some configuration changes, one could use with any PHP project, such as those using Symfony. Static code analysis is a source code structure analysis and test without running or compiling the code. Although it will not find all potential problems and bugs and is not replacing code review, it could be beneficial, especially in bigger teams.

Why should you use static code analysis?

In my opinion, the main advantages of using SAST (Static Analysis Software Testing) tools are how fast they run and the possibility to integrate them with continuous integration software. The automation of such analysis and integration with CI tools IDEs make them easy to enforce for all team members. They are an easy and fast way to find simple bugs that require a small effort to fix. You could start with almost no configuration, making it easy to implement in the software development cycle. Later, based on your experience, you could extend your configuration or write new rules to help your team achieve better results.

Using static code analysis helps:

Before you start using static code analysis, please make sure that you understand the below points:

Four levels of static code analysis.

Usually, for Laravel projects, I use four open-source tools for static code analysis. It seems that static code analysis is not very popular among PHP developers. However, likely, you are already using at least the first one of the below tools.

Linter: PHP Parallel Lint.

Linter or lint is a common name used for tools performing static code analysis. Historically, it was a tool to analyze C programs lexically. The primary function was to warn about syntax errors, undeclared variables, use of deprecated functions, etc. The PHP has a built-in lint-like function. Just call php -l filename.php to run it.

As you could imagine, it could be hard to call it manually for every source file in Laravel or Symfony applications. PHP Parallel Lint is a tool that at its core does what php -l does but in parallel (10 jobs by default), recursively and returns a fancier output.

Install it with composer require --dev php-parallel-lint/php-parallel-lint and run for example with vendor/bin/parallel-lint directory_name.

If you are using a more complex IDE, you are already doing some lint during editing source code. As a part of static code analysis, this tool will help you make sure all developers are using this test and covering all source files.

Code syntax versus PSR standards: PHP_CodeSniffer.

If you are not yet aware of PSR (PHP Standards Recommendations), you should fill that knowledge gap as soon as possible. If you are aware, you should probably know PSR-1 and PSR-2, both describing coding standards.

If you did not think while reading the above paragraph that I made a mistake about PSR-2, you should also refresh your knowledge. PHP-FIG deprecated PSR-2 in favor of PSR-12. If you do not do it already, start writing according to PSR-12 where you can.

Let’s go back to the topic. If you use IDE, you should have an option to configure it to help you write according to PSR standards. Similar to the problem with linter, non all developers could or would use such IDE syntax aid. That is why you should include a tool in your development cycle to validate your code with PSR standards.

PHP_CodeSniffer is my choice to check my code against PHP coding standards. To install it run composer require --dev squizlabs/php_codesniffer. After that, you could run it with just vendor/bin/phpcs directory_name.

By default, PHP_CodeSniffer validates and reports violations to PEAR coding standards. For Laravel, you would instead use the option --standard=PSR12 along with the run command.

Static analysis: PHP Mess Detector

PHP Mess Detector provides a set of diverse rules to analyze source code and report problems like unused code, overcomplicated expressions, possible bugs, and not optimal code. It comes with a set of rules (rulesets) that you could use to analyze your code.

To install PHP Mess Detector run the following Composer command composer require --dev phpmd/phpmd. It is the first tool on my list where you would probably need to create some configuration file to run and analyze your code.

PHPMD comes with multiple report renderers from which you would need to choose. While XML or JSON file could help some more in-depth analyses, I will use text or ansi while running it from the command line. Besides renderer, PHPMD will require a list of rules or rulesets. We could run it using vendor/bin/phpmd directory_name text cleancode,codesize.

For Laravel, some of the rules will give us some potential false positives, like static access or many children classes. My personal preference is also excluding minimum and maximum variable length. Below you will find a configuration template I use as a starter for the final configuration. Save it as an XML file and add it as a parameter when running PHPMD.

<?xml version="1.0"?>
<ruleset name="Custom_PHPMD">
    <description>Custom ruleset PHPMD</description>
    <rule ref="rulesets/cleancode.xml">
        <exclude name="ElseExpression"/>
        <exclude name="StaticAccess"/>
    </rule>
    <rule ref="rulesets/codesize.xml"/>
    <rule ref="rulesets/controversial.xml"/>
    <rule ref="rulesets/design.xml">
        <exclude name="NumberOfChildren"/>
        <exclude name="CouplingBetweenObjects"/>
    </rule>
    <rule ref="rulesets/design.xml/CouplingBetweenObjects">
        <properties>
            <property name="minimum" value="20"/>
        </properties>
    </rule>
    <rule ref="rulesets/naming.xml">
        <exclude name="ShortVariable"/>
        <exclude name="LongVariable"/>
    </rule>
    <rule ref="rulesets/unusedcode.xml"/>
</ruleset>

Static analysis: Larastan

Another tool working like PHP Mess Detector is PHPStan. It uses levels (nine at the moment of writing this article), similar to rulesets in PHPMD. Although you could use PHPStan in your Laravel application, the better decision would be to use Larastan, which extends PHPStan with rules and configuration specific for Laravel.

To install it, run composer require --dev nunomaduro/larastan. It will install PHPStan as a dependency. You could run vendor/bin/phpstan analyse directory_name but it will not use Larastan extensions. However, it will run PHPStan with the default level of rules.

To make sure we will be using correct extensions, let’s create a phpstan.neon configuration file and include Larastan extensions. We could set the paths, the rules level, ignored rules, and other configuration variables. For my Laravel projects, I use the below content as a starter for the final configuration.

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:
    paths:
        - app
        - tests
    level: 7
    checkMissingIterableValueType: false

Wrap up.

Both PHP Mess Detector and PHPStan or Larastan with a default configuration, or even with those starting one available above, will in mature project show you a lot of problems. With a big codebase or old code that you did not analyze before, you should probably start with fewer rules and lower levels. Then gradually increase them as soon as you fix them.

Running all of those tools every time you are ready to push your changes would be a little tiring. I usually use composer scripts to create a command to run all tests - something like the example below.

"scripts": {
    "static-analyse": [
        "parallel-lint app tests",
        "phpcs --standard=PSR12 app tests",
        "phpmd app,tests ansi phpmd.xml",
        "phpstan analyse"
    ]
}

All static code analysis tools described above, by design, fit into the continuous integration approach and exit with an error code when they found violations. Thanks to that next commands would not run when the previous failed, and the order does matter.

Keep in mind that it is not a full list of possible static code analysis tools available for PHP applications in general and Laravel in specific. However, it is a good starting point for you to find your best tools, which will allow you and your team to write better code, do fewer bugs and decrease the effort to fix them.

devopsdevelopmentphplaravelcontinuous integrationstatic code analysiscode review
See Also
This site uses cookies to analyze traffic and for ads measurement purposes according to your browser settings. Access to those cookies is shared with Google to generate usage statistics and detect and address abuse. Learn more about how we use cookies.