PHPStan: Improve the Quality of Your PHP Code

Walter Nascimento - Sep 9 - - Dev Community

What is PHPStan?

PHPStan (PHP Static Analysis Tool) is a tool that analyzes PHP code to find bugs and issues without executing it. It does this by examining the source code and checking for inconsistencies, such as incorrect variable types, method calls on null objects, and other common mistakes. This is done through static analysis, which is the examination of code without executing it.

Installing PHPStan

To get started with PHPStan, you need to install it in your project. The most common way to install PHPStan is via Composer. Follow these steps to install it:

Install PHPStan via Composer

Open a terminal and run the following command to add PHPStan as a development dependency to your project:

composer require --dev phpstan/phpstan
Enter fullscreen mode Exit fullscreen mode

The --dev flag ensures that PHPStan is installed as a development dependency only.

Verify the Installation

After installation, you can verify if PHPStan was installed correctly by running:

vendor/bin/phpstan --version
Enter fullscreen mode Exit fullscreen mode

This should display the installed version of PHPStan.

Configuring PHPStan with .neon File

PHPStan can be configured using a .neon configuration file. This file allows you to define rules, configure analysis levels, and tailor the analysis to your specific project needs.

Basic .neon Configuration File

Here is a basic example of PHPStan configuration using a .neon file:

parameters:
    level: 7
    paths:
        - src
Enter fullscreen mode Exit fullscreen mode

Explanation of Configurations

  • level: Defines the rigor level of the analysis. 7 is quite strict, but you can adjust it as needed.
  • paths: Defines the directories PHPStan should analyze. In the example, the src directory is analyzed.

Creating Configuration Files for the Team and Ignoring Personal Configurations in Git

It’s a good practice to create a general configuration file for the team and add a .gitignore to avoid versioning personal configurations.

Create a general project configuration file, for example, phpstan.neon:

includes:
    - phpstan.dist.neon

parameters:
    level: 6

    ignoreErrors:
        - '#Attribute class JetBrains\\PhpStorm\\Pure does not exist#'
        - '#Attribute class JetBrains\\PhpStorm\\NoReturn does not exist#'
Enter fullscreen mode Exit fullscreen mode

And a team-specific configuration file, for example, phpstan.dist.neon:

parameters:
    level: max
    paths:
        - src
Enter fullscreen mode Exit fullscreen mode

Add personal configuration files to .gitignore to keep them out of version control:

phpstan.neon
Enter fullscreen mode Exit fullscreen mode

How to Run PHPStan

Once PHPStan is installed and configured, you can run it to analyze your code. Here are the basic commands to run PHPStan:

Run Analysis

To run a basic analysis using the default configuration (your phpstan.neon file), use the following command:

vendor/bin/phpstan analyse
Enter fullscreen mode Exit fullscreen mode

This command performs static analysis of your PHP code as defined in the .neon configuration file.

Run Analysis with Specific Configuration

If you have multiple configuration files and want to specify which one to use, you can use the --config option:

vendor/bin/phpstan analyse --config=phpstan-team.neon
Enter fullscreen mode Exit fullscreen mode

This command allows you to choose which configuration to apply during the analysis.

Check Analysis Levels

PHPStan allows you to set rigor levels from 0 to 8. Higher levels provide more stringent analysis. To run the analysis with a specific level, you can set the level directly in the command:

vendor/bin/phpstan analyse --level=max
Enter fullscreen mode Exit fullscreen mode

The max level is the most stringent, and you can replace max with a specific number as needed.

Example of Before and After

Original Code (Before)

Consider the following PHP code that manipulates a user array:

function getUserAge(array $user): int {
    return $user['age'];
}

$user = [
    'name' => 'John Doe',
    // 'age' is missing
];

$age = getUserAge($user);
echo "User age: $age";
Enter fullscreen mode Exit fullscreen mode

PHPStan Analysis

When PHPStan analyzes the above code, it may point out that the age index is missing in the $user array, but the code tries to access it directly. This could lead to a runtime error if the age index is not present in the array.

Adjusted Code (After)

To fix this and meet PHPStan’s expectations, you can adjust the function to check if the age index is present before accessing it:

function getUserAge(array $user): int {
    if (!isset($user['age'])) {
        throw new RuntimeException('Age is not set in the user array');
    }

    return $user['age'];
}

$user = [
    'name' => 'John Doe',
    // 'age' is still missing, but now the code throws an exception if it’s missing
];

try {
    $age = getUserAge($user);
    echo "User age: $age";
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}
Enter fullscreen mode Exit fullscreen mode

Explanation of Changes

  • Index Existence Check: Adds a check to ensure the age index is present in the array before accessing it.
  • Exception Handling: Throws an exception if the age index is missing and handles the exception when calling the function.

Conclusion

PHPStan is a powerful tool for improving the quality of your PHP code through static analysis. Installing it is simple and quick with Composer. Configuring it correctly and adjusting its rules can help you find and fix issues before they become real bugs. Use the .neon file to customize PHPStan’s configuration, and remember to add personal configuration files to .gitignore to keep your repository clean and organized.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .