Skip to main content

Drupal

How to Fix Coding Issues Using PHPStan in Drupal

Group Of Developers

Regarding Drupal projects, PHPStan is a great command line tool for seeing how your PHP code is doing without running it. It’s great for finding potential bugs other tools and unit tests couldn’t find.

There is a small problem that PHPStan does not know how to interpret Drupal plugins, entities, controllers, or other Drupal architecture that goes into Drupal modules. Because of this, when you try to run PHPStan on your module code, you’ll find that it generates a lot of errors about missing objects and wrong parameters.

So, let’s get this installed in your Drupal project.

Steps to Install PHPStan in Drupal Project

Step 1:

To install PHPstan into your project, open the terminal and execute the below command in your project root directory.

composer require --dev phpstan/phpstan phpstan/extension-installer mglaman/phpstan-drupal phpstan/phpstan-deprecation-rules

Install PHPStan using composer in Drupal

Step 2:

After installing PHPStan, we need to configure the settings for PHPStan to find errors in our code.

Create a new file in your project root directory called phpstan.neon and add the configuration below.

parameters:
    level: 0
    paths:
        - docroot/modules/custom
    editorUrl: 'phpstorm://open?file=%%file%%&line=%%line%%'

Set PHPStan configuration to identify Drupal project code errors.

Initially, we are setting the PHPStan error check level to 0. So, it will do the basic checks in your code. We can change it according to our level of code complexity.

Here’s a quick overview of what is checked at each level. Levels are cumulative. For example, if you go to level 5, you get all checks from levels 0 to 4.

  1. Basic checks, unknown classes, unknown functions, unknown methods called by $this, incorrect number of arguments passed to these methods and functions, always undefined variables.
  2. Potentially undefined variables, unknown magic methods, and class properties with __call and __get.
  3. Unknown methods checked for all expressions (not just $this), PHPDocs verification.
  4. Return type is the type assigned to a property.
  5. For basic checks, dead code – and other instances of type checking are always wrong, else branch is dead, in code after return unreachable, etc.
  6. Check types of arguments passed to methods and functions.
  7. Report missing type hints.
  8. Report partially wrong union types – some types of union types Reporting starts at level 7 when calling a method that exists only in.
  9. Reporting method calls and accesses properties of nullable types.
  10. Be strict with mixed types – the only legal operation that can be performed on a mixed type is passing it to another mixed type.

Step 3:

Now, execute the command below in the terminal to generate a PHPStan errors report.

php ./vendor/bin/phpstan

It will generate PHPStan errors report. The default format will be table format to display all errors.

Error list of Drupal project code using PHPStan.

 

If you are facing a memory problem, use this command with –memory-limit option.

php ./vendor/bin/phpstan --memory-limit=1G

Also, You can generate this error report in a different format. Here is an example of generating this report in JSON format.

php ./vendor/bin/phpstan --error-format=json --no-progress --ansi > phpstan_analysis.json

Here, phpstan_analysis.json is a file name in which all errors will generate. It will be generated in the root directory of the project folder.

 

A Common Problem When Analysing Drupal Code Using PHPStan

When generating the PHPStan report, I found multiple issues in files regarding the below error.

Unsafe usage of new static().

Unsafe usage of new static().

Unsafe usage of new static() in Drupal code.

This is because we are using dependency injection and calling services using ContainerInterface.

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition
    );
  }

Container Interface for di.

PHPStan throws this error because extending a class and overriding the constructor with other parameters can break it.

There’s some information on why this use of new static() is unsafe on the PHPStan website.

See: Fix “unsafe usage of new static()” in Drupal code.

 

To ignore this error in a report, you must add the below configuration in phpstan.neon file.

Add ignoreErrors to avoid unwanted errors in Drupal code.

Adding this option turns off that error and means we can focus on other things important to improving the code quality of the custom code.

Conclusion

PHPStan is a great tool and should be part of your development workflow. Using this, we can improve our code quality and efficiency. We were successfully able to generate a PHPStan error report in the Drupal project, and we learned how to exclude errors that are not actual errors.

 

Thoughts on “How to Fix Coding Issues Using PHPStan in Drupal”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Rohit Bhasarkar, Associate Technical Consultant

Rohit Bhasarkar works for Perficient in Nagpur GDC as an Associate Technical Consultant. He has more than 3 years of experience in different technologies. Rohit is currently working on Magento and Drupal technologies as a backend developer. He likes to explore new challenges in technology. Rohit is eager to increase his coding knowledge and develop his coding abilities.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram