How to Find Bugs Faster with PHP Stan?

Let me introduce you to PHPStan - a powerful tool that helps detect bugs before they reach production.

I was wondering how to best introduce this tool to you. After some thought, I realized the best way is to let the creators speak for themselves. So, let me introduce you to PHPStan - powerful tool that helps detect bugs before they reach production.


What’s PHP Stan?

PHPStan is a tool that helps identify issues in PHP code. It checks the codebase for syntax mistakes, type errors, or incorrect function calls, analyzes the data flow, and looks for unused code or missing return statements. It works best with object-oriented strongly typed or well-annotated code, so that's another reason why it's worth giving OOP a spin.

Image


Why to Use PHP Stan?

Let's run a quick test. How many issues can you spot in this code within 10 seconds? If you find at least two, you're on the right track. However, there are many more to uncover 🫷

namespace FM;

class Test
{
    public function __construct()
    {
        $this->call();
    }

    private function log(string $message): void
    {
        error_log($message);
    }

    private function call()
    {
        $this->log(1);

        return get_posts(1);
    }

    private function notify()
    {
        if (true) {
            return;
        }

        return '';
    }
}

There are at least four potential issues to be aware of. Three are non-critical, meaning the application may still work but could produce a warning. There is, however, one critical factor that could affect the business results.

LineIssue
Incorrect value passed to get_posts function. WordPress requires an array of WP_Query arguments instead.
Incorrect value passed to the log function which requires string, but int is passed.
Unreachable code caused by the condition that is always true.
The notify function is private and never used.

Some time after I created this simple class with the specific problems in mind, I forgot where some of the issues were located. It took me a while to figure out what was wrong. This experience highlights how time-consuming manual code analysis can be.

Image

In my career, I have already spent a huge amount of time reading through code and searching for problems, whereas PHPStan could identify all of them in less than a second.

So, why it's worth to use PHPStan? To save time and provide better results. PHPStan gives immediate feedback on the code quality, so developers can fix bugs not only before reaching the production server but even before reaching the repository. The tool helps create code that works better, is more compact, and performs tasks with less effort.

Image


How to Install PHP Stan?

The easiest way to install PHP Stan is by using Composer. Simply open the terminal, navigate to the WordPress project root directory, and run the following command. If you're not yet familiar with Composer, refer to a guide to get started. [🔗]

composer require --dev phpstan/phpstan

How to Use PHP Stan?

To let PHPStan analyze your codebase, you have to use the analyze command and point it to the right directory. For example, if the project's PHP files are located in app and inc folders, you should run the following command 👇 to let PHP Stan analyze the code.

vendor/bin/phpstan analyze app inc  --memory-limit=2048M

15/15 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

[OK] No errors

The tool verified all the PHP files located there and informed that there's no error to fix yet.

To make using the tool easier, add a script to your project's composer.json file. This will allow you to run PHP Stan with a simple composer analyze command rather than the longer version.

{
  "scripts": {
    "lint": "phpcs",
    "format": "phpcbf",
    "analyze": "phpstan analyse app inc --memory-limit=2048M"
  },
}
composer analyze

15/15 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

[OK] No errors

How to Configure PHP Stan?

Instead of setting up the tool each time with command-line arguments, you can simplify this process by creating a project configuration file named phpstan.neon. This file is automatically resolved when you run the analyze command.

parameters:
    level: 6
    paths:
        - inc
        - app

For instance, rather than repeatedly typing in directory paths in the command line whenever you want to inspect the code, you can list these directories once in the configuration file. There are many other settings, so be sure to check the documentation.


How to Ignore PHP Stan Errors?

You might want to ignore some errors found by PHPStan for various reasons, for instance, you can’t find the stubs you’re looking for or it’s a known bug and you don’t have time to wait for a bugfix. Fortunately, there are a few ways to handle this.

  1. Comments: By comments as with other analysis tools like phpcseslint, or stylelint. Put the @phpstan-ignore comment near the line you want to ignore and specify the error code.
  2. Configuration: By regular expressions in the configuration file under the ignoreErrors key.
  3. Baseline: Since I'm less familiar with this, I recommend referring to the official docs.
// @phpstan-ignore-next-line variable.undefined
echo $foo;

echo $foo; // @phpstan-ignore variable.undefined

How to Use PHP Stan with WordPress?

Running composer analyze command in our WordPress theme in the current state causes many errors, mostly related to undefined WordPress functions. That’s because a few more steps are needed to ensure PHPStan works in WordPress.

Image

The current configuration tells PHPStan to check only the app and inc directories, but WordPress functions are not defined there. They are defined in other layers, higher in the hierarchy, so PHPStan doesn’t recognize them.

To fix this, you'll need to install and load a WordPress extension for PHPStan. Navigate to the theme’s root, install the extension using composer with the command above, and include its extension.neon in the configuration file within the includes property.

composer require --dev szepeviktor/phpstan-wordpress
parameters:
    level: 6
    paths:
        - inc
        - app
includes:
    - vendor/szepeviktor/phpstan-wordpress/extension.neon

When you run the tool now, there are no more errors about missing WordPress functions. However, there are other errors indicating that something is missing. They are related to the constants defined in the theme, so why are they not resolved?

Image

That’s again the matter of the tool configuration, which tells PHP Stan to check only the app and inc directories of the theme, while the missing constants are defined in the theme's entry file, which is located elsewhere. To address this, include the files that should be loaded before the analyzing process in the bootstrapFile key of the configuration.

parameters:
    level: 5
    paths:
        - inc
        - app
    bootstrapFiles:
        - resources/functions.php
includes:
    - vendor/szepeviktor/phpstan-wordpress/extension.neon

Running the analysis process in its current form produces significantly fewer errors. The remaining issues are tied to the codebase and require manual resolution.

Image


How to Use PHP Stan with ACF?

Advanced Custom Fields is a popular plugin often integrated in themes or plugins. To solve problems with missing ACF functions like get_field in PHP Stan, install ACF stub files and include them in the tool configuration file.

composer require --dev php-stubs/acf-pro-stubs
parameters:
    level: 5
    paths:
        - inc
        - app
    bootstrapFiles:
        - resources/functions.php
    scanFiles:
        - vendor/php-stubs/acf-pro-stubs/acf-pro-stubs.php
includes:
    - vendor/szepeviktor/phpstan-wordpress/extension.neon

This problem highlights the matter of dependency hell. The more external methods and classes you integrate into your WordPress project, the more stubs you'll need to add. To find them, try searching for the plugin name along with "stubs" on Google. If you can't find the required stubs, consider ignoring certain types of errors, as explained in the next section.


How to Use PHP Stan with VS Code?

Like other linters such as StylelintESLint, or phpcs, you can configure VS Code to display issues as you write code. Simply install the extension. This is useful because it allows you to spot bugs right after they are created.


How to Resolve Reported Errors?

After configuring PHP Stan, two errors are left in the codebase. It’s already visible that the tool works great and is already helping us write more efficient code.

Image

  1. The first issue points out an unnecessary check for whether a value is empty. This is valid since the $instance has an object type so it’s never empty. It can be removed.
  2. The second issue highlights that a Resolver class instance is being assigned to private class property but it’s never used again, so actually there’s no need to assign it to the class property. The class can be initialised itself.

Image

The tool correctly analyzed the code, identified two issues, and contributed to reducing the size of the codebase. And don’t let yourself think that removing a few lines is nothing to be proud of. Consider the bigger picture. In real-world projects, achieving even a small reduction in the codebase size is a significant gain. Also, as Erling Harland once said, „stay humble”. PHP Stan won’t replace you as a tester. It only helps to find trivial bugs.


If you enjoyed this article, please give it a thumbs up and consider subscribing for more content like this! Don't forget to check out my social profiles for updates and behind-the-scenes content. I'd love to hear from you, so drop a comment below with your thoughts.

avatar

Looking For a Developer Who
Truly Cares About Your Business?

My team and I provide expert consultations, top-notch coding, and comprehensive audits to elevate your success.

Feedback

How satisfied you are after reading this article?