19/06/2018 - PHING, PHP, SYMFONY
The aim of PHPStan is to scan application code to find errors without actually running it. Since PHP is not a compiled language it often tends to crash in production only when a code with errors gets used. PHPStan is used to find errors before code being deployed to production.
Use $ composer require --dev phpstan/phpstan
to install the library.
By default you can start using it with $ vendor/bin/phpstan analyse src --level max
command. You can reduce "strictness" level as per your needs.
Sometimes you might need to create your own configuration file phpstan.neon
with certain rules. This is optional but let's see a few basics when it comes to working with one. You can check vendor/phpstan/phpstan/conf
folder for the actual rule files to see what they look like. Create "phpstan.neon" file in your project root with content below and run $ vendor/bin/phpstan analyse src -c phpstan.neon
command.
parameters:
# Needed only when you use "rules" block below
customRulesetUsed: true
# Sometimes needed
autoload_files:
- %rootDir%/../../../vendor/autoload.php
# Prevents scanning given folders/files
excludes_analyse:
- %rootDir%/../../../src/Migrations/*
# You specific list of rules
rules:
- PHPStan\Rules\Arrays\DuplicateKeysInLiteralArraysRule
If you are not manually requiring phpunit/phpunit
component in your composer.json file and relying on Symfony's PHPUnit Bridge instead, you will probably face similar errors as shown below.
Class PHPUnit\Framework\TestCase not found and could not be autoloaded.
Class [a test class of yours] was not found while trying to analyse it - autoloading is probably not configured properly.
Do the following to solve the first issue.
$ find -iname 'autoload.php'
command to identify the path to the PHPUnit's autoloader file.autoload_files
section of the PHPStan's configuration file. e.g. - %rootDir%/../../../bin/.phpunit/phpunit-6.5/vendor/autoload.php
Add code below to the parameters
section of the PHPStan's configuration file to solve the second issue.
autoload_directories:
- %rootDir%/../../../tests