TheCodingMachine's additional rules for PHPStan
This package contains a set of rules to be added to the wonderful PHPStan static analyzer.
Those rules come from TheCodingMachine best practices. They are more "strict" than the default PHPStan rules and some may be controversial. We use those at TheCodingMachine, have found them to help us in our daily work, and ask anyone working with us to follow them.
Exception related rules
- You should not throw the "Exception" base class directly but throw a sub-class instead.
- You should not have empty catch statements
- When throwing an exception inside a catch block, you should pass the catched exception as the "previous" exception
Type-hinting related rules
This is a PHP 7.1+ rule:
- You should use type-hinting when possible
- If not possible, you should use a Docblock to specify the type
- If type-hinting against an array, you should use a Docblock to further explain the content of the array
Superglobal related rules
- The use of
$_REQUESTis forbidden. You should instead use your framework's request/session object.
- Superglobal usage is still tolerated at the root scope (because it is typically used once in
index.phpto initialize PSR-7 request object)
Condition related rules
- Switch statements should always check for unexpected values by implementing a default case (and throwing an exception)
// Never use public properties // Never use globals
We assume that PHPStan is already installed in your project.
Let's add this package:
composer require --dev thecodingmachine/phpstan-strict-rules
Now, edit your
phpstan.neon file and add these rules:
includes: - vendor/thecodingmachine/phpstan-strict-rules/phpstan-strict-rules.neon