Integrating PHPStan in PHPStorm / PHPStan Pro
PHPStan is a static code analyzer for PHP which can reduce the amount of bugs in a project and make it more maintainable in the long run. With the latest release of PHPStorm 2020.3 EAP, support for PHPStan is provided directly by PHPStorm - no plugins necessary.
Let's take a look at how that can be configured and used.
Installing PHPStan
We need to install and configure PHPStan - thankfully, there already is a handy blog post we can follow.
Basically, require PHPStan with Composer and get started. In my case I added the extension installer and TYPO3 extension, too, as I want to use it for my TYPO3 extension development:
composer require --dev phpstan/phpstan
composer require --dev phpstan/extension-installer
composer require --dev saschaegerer/phpstan-typo3:@dev
Next, I created a basic config file:
with this content:
parameters:
level: max
paths:
- ../Classes
Now we need to tell PHPStorm where to find both PHPStan and the configuration file.
Configure PHPStan in PHPStorm
Configure PHPStan Location in PHPStorm
- Go to
File > Settings
- Open
Languages & Frameworks > PHP > Quality Tools
- Expand
PHPStan
- Choose your PHP Interpreter at
Configuration
- Click on
...
- Configure the path to your
phpstan
executable (in a composer installation most likely<projectpath>/vendor/bin/composer
) - Click on
Validate
to ensure PHPStorm finds it - Save
Configure PHPStan (Config File, Inspection) in PHPStorm
- Go to
File > Settings
- Open
Editor > Inspections
- Expand
PHP > Quality tools
- Check the checkbox at
PHPStan Global validation
- Set the severity you want
- If you have a custom configuration file, add it here
- Click
Apply
After closing the settings, PHPStorm will now automatically inspect your code according to your configuration.
PHPStan Pro
In case you are just getting started with PHPStan or want to use PHPStan in a legacy project, in addition of using the PHPStorm integration I would recommend to take a closer look at PHPStan Pro.
PHPStan Pro comes with a nice GUI and continuous inspections. You can start it via the command line
by running vendor/bin/phpstan analyse -c Build/phpstan.neon --pro
- a browser window will open
asking you to login. After login, you will get a list of errors / warnings that is updated as you code.
I have that window running on a second screen to continuously watch my code getting better.
PHPStan Pro additionally provides interactive fixing of errors through the GUI.
Even if you don't need the PHPStan Pro features, I'd ask you to consider buying a
license if possible as it supports the creator who is providing the main tool for free.