| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even before you write tests for the code.
PHPStan moves PHP closer to compiled languages in the sense that the correctness of each line of the code can be checked before you run the actual line.
Read more about PHPStan on Medium.com »
Try out PHPStan on the on-line playground! »
I offer to issue invoices for contributions on PayPal and Patreon! Contact me for details.
It currently performs the following checks on your code:
Unique feature of PHPStan is the ability to define and statically check "magic" behaviour of classes - accessing properties that are not defined in the class but are created in __get and __set and invoking methods using __call.
See Class reflection extensions and Dynamic return type extensions.
You can also install official framework-specific extensions:
Unofficial extensions for other frameworks and libraries are also available:
New extensions are becoming available on a regular basis!
PHPStan requires PHP >= 7.0. You have to run it in environment with PHP 7.x but the actual code does not have to use PHP 7.x features. (Code written for PHP 5.6 and earlier can run on 7.x mostly unmodified.)
PHPStan works best with modern object-oriented code. The more strongly-typed your code is, the more information you give PHPStan to work with.
Properly annotated and typehinted code (class properties, function and method arguments, return types) helps not only static analysis tools but also other people that work with the code to understand it.
To start performing analysis on your code, require PHPStan in Composer:
composer require --dev phpstan/phpstan
Composer will install PHPStan's executable in its bin-dir which defaults to vendor/bin.
If you have conflicting dependencies or you want to install PHPStan globally, the best way is via a PHAR archive. You will always find the latest stable PHAR archive below the release notes. You can also use the phpstan/phpstan-shim package to install PHPStan via Composer without the risk of conflicting dependencies.
You can also use PHPStan via Docker.
To let PHPStan analyse your codebase, you have use the analyse command and point it to the right directories.
So, for example if you have your classes in directories src and tests, you can run PHPStan like this:
vendor/bin/phpstan analyse src testsPHPStan will probably find some errors, but don't worry, your code might be just fine. Errors found on the first run tend to be:
After fixing the obvious mistakes in the code, look to the following section for all the configuration options that will bring the number of reported errors to zero making PHPStan suitable to run as part of your continuous integration script.
If you want to use PHPStan but your codebase isn't up to speed with strong typing and PHPStan's strict checks, you can choose from currently 8 levels (0 is the loosest and 7 is the strictest) by passing --level to analyse command. Default level is 0.
This feature enables incremental adoption of PHPStan checks. You can start using PHPStan with a lower rule level and increase it when you feel like it.
You can also use --level max as an alias for the highest level. This will ensure that you will always use the highest level when upgrading to new versions of PHPStan. Please note that this can create a significant obstacle when upgrading to a newer version because you might have to fix a lot of code to bring the number of errors down to zero.
Config file is passed to the phpstan executable with -c option:
vendor/bin/phpstan analyse -l 4 -c phpstan.neon src testsWhen using a custom project config file, you have to pass the --level (-l) option to analyse command (default value does not apply here).
If you do not provide config file explicitly, PHPStan will look for files named phpstan.neon or phpstan.neon.dist in current directory.
The resolution priority is as such:
NEON file format is very similar to YAML. All the following options are part of the parameters section.
PHPStan uses Composer autoloader so the easiest way how to autoload classes is through the autoload/autoload-dev sections in composer.json.
If PHPStan complains about some non-existent classes and you're sure the classes exist in the codebase AND you don't want to use Composer autoloader for some reason, you can specify directories to scan and concrete files to include using autoload_directories and autoload_files array parameters:
parameters: autoload_directories: - %rootDir%/../../../build autoload_files: - %rootDir%/../../../generated/routes/GeneratedRouteList.php
%rootDir% is expanded to the root directory where PHPStan resides.
PHPStan supports global installation using composer global or via a PHAR archive. In this case, it's not part of the project autoloader, but it supports autodiscovery of the Composer autoloader from current working directory residing in vendor/:
cd /path/to/project
phpstan analyse src tests # looks for autoloader at /path/to/project/vendor/autoload.phpIf you have your dependencies installed at a different path or you're running PHPStan from a different directory, you can specify the path to the autoloader with the --autoload-file|-a option:
phpstan analyse --autoload-file=/path/to/autoload.php src testsIf your codebase contains some files that are broken on purpose (e. g. to test behaviour of your application on files with invalid PHP code), you can exclude them using the excludes_analyse array parameter. String at each line is used as a pattern for the fnmatch function.
parameters: excludes_analyse: - %rootDir%/../../../tests/*/data/*
If your codebase contains php files with extensions other than the standard .php extension then you can add them to the fileExtensions array parameter:
parameters: fileExtensions: - php - module - inc
Classes without predefined structure are common in PHP applications. They are used as universal holders of data - any property can be set and read on them. Notable examples include stdClass, SimpleXMLElement (these are enabled by default), objects with results of database queries etc. Use universalObjectCratesClasses array parameter to let PHPStan know which classes with these characteristics are used in your codebase:
parameters: universalObjectCratesClasses: - Dibi\Row - Ratchet\ConnectionInterface
If you use some variables from a try block in your catch blocks, set polluteCatchScopeWithTryAssignments boolean parameter to true.
try {
$author = $this->getLoggedInUser();
$post = $this->postRepository->getById($id);
} catch (PostNotFoundException $e) {
// $author is probably defined here
throw new ArticleByAuthorCannotBePublished($author);
}If you are enumerating over all possible situations in if-elseif branches and PHPStan complains about undefined variables after the conditions, you can write an else branch with throwing an exception:
if (somethingIsTrue()) {
$foo = true;
} elseif (orSomethingElseIsTrue()) {
$foo = false;
} else {
throw new ShouldNotHappenException();
}
doFoo($foo);I recommend leaving polluteCatchScopeWithTryAssignments set to false because it leads to a clearer and more maintainable code.
Previous example showed that if a condition branches end with throwing an exception, that branch does not have to define a variable used after the condition branches end.
But exceptions are not the only way how to terminate execution of a method early. Some specific method calls can be perceived by project developers also as early terminating - like a redirect() that stops execution by throwing an internal exception.
if (somethingIsTrue()) {
$foo = true;
} elseif (orSomethingElseIsTrue()) {
$foo = false;
} else {
$this->redirect('homepage');
}
doFoo($foo);These methods can be configured by specifying a class on whose instance they are called like this:
parameters: earlyTerminatingMethodCalls: Nette\Application\UI\Presenter: - redirect - redirectUrl - sendJson - sendResponse
If some issue in your code base is not easy to fix or just simply want to deal with it later, you can exclude error messages from the analysis result with regular expressions:
parameters: ignoreErrors: - '#Call to an undefined method [a-zA-Z0-9\\_]+::method\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::expects\(\)#' - '#Access to an undefined property PHPUnit_Framework_MockObject_MockObject::\$[a-zA-Z0-9_]+#' - '#Call to an undefined method PHPUnit_Framework_MockObject_MockObject::[a-zA-Z0-9_]+\(\)#'
If some of the patterns do not occur in the result anymore, PHPStan will let you know and you will have to remove the pattern from the configuration. You can turn off this behaviour by setting reportUnmatchedIgnoredErrors to false in PHPStan configuration.
If you need to initialize something in PHP runtime before PHPStan runs (like your own autoloader), you can provide your own bootstrap file:
parameters: bootstrap: %rootDir%/../../../phpstan-bootstrap.php
PHPStan allows writing custom rules to check for specific situations in your own codebase. Your rule class needs to implement the PHPStan\Rules\Rule interface and registered as a service in the configuration file:
services: - class: MyApp\PHPStan\Rules\DefaultValueTypesAssignedToPropertiesRule tags: - phpstan.rules.rule
For inspiration on how to implement a rule turn to src/Rules to see a lot of built-in rules.
Check out also phpstan-strict-rules repository for extra strict and opinionated rules for PHPStan!
By default, PHPStan outputs found errors into tables grouped by files to be easily human-readable. To change the output, you can use the --errorFormat CLI option. There's an additional built-in raw format with one-per-line errors intended for easy parsing. You can also create your own error formatter by implementing the PHPStan\Command\ErrorFormatter\ErrorFormatter interface:
interface ErrorFormatter
{
/**
* Formats the errors and outputs them to the console.
*
* @param \PHPStan\Command\AnalysisResult $analysisResult
* @param \Symfony\Component\Console\Style\OutputStyle $style
* @return int Error code.
*/
public function formatErrors(
AnalysisResult $analysisResult,
\Symfony\Component\Console\Style\OutputStyle $style
): int;
}Register the formatter in your phpstan.neon:
errorFormatter.awesome: class: App\PHPStan\AwesomeErrorFormatter
Use the name part after errorFormatter. as the CLI option value:
vendor/bin/phpstan analyse -c phpstan.neon -l 4 --errorFormat awesome src testsClasses in PHP can expose "magical" properties and methods decided in run-time using class methods like __get, __set and __call. Because PHPStan is all about static analysis (testing code for errors without running it), it has to know about those properties and methods beforehand.
When PHPStan stumbles upon a property or a method that is unknown to built-in class reflection, it iterates over all registered class reflection extensions until it finds one that defines the property or method.
Class reflection extension cannot have PHPStan\Broker\Broker (service for obtaining class reflections) injected in the constructor due to circular reference issue, but the extensions can implement PHPStan\Reflection\BrokerAwareExtension interface to obtain Broker via a setter.
This extension type must implement the following interface:
namespace PHPStan\Reflection;
interface PropertiesClassReflectionExtension
{
public function hasProperty(ClassReflection $classReflection, string $propertyName): bool;
public function getProperty(ClassReflection $classReflection, string $propertyName): PropertyReflection;
}Most likely you will also have to implement a new PropertyReflection class:
namespace PHPStan\Reflection;
interface PropertyReflection
{
public function getType(): Type;
public function getDeclaringClass(): ClassReflection;
public function isStatic(): bool;
public function isPrivate(): bool;
public function isPublic(): bool;
}This is how you register the extension in project's PHPStan config file:
services: - class: App\PHPStan\PropertiesFromAnnotationsClassReflectionExtension tags: - phpstan.broker.propertiesClassReflectionExtension
This extension type must implement the following interface:
namespace PHPStan\Reflection;
interface MethodsClassReflectionExtension
{
public function hasMethod(ClassReflection $classReflection, string $methodName): bool;
public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection;
}Most likely you will also have to implement a new MethodReflection class:
namespace PHPStan\Reflection;
interface MethodReflection
{
public function getDeclaringClass(): ClassReflection;
public function getPrototype(): self;
public function isStatic(): bool;
public function isPrivate(): bool;
public function isPublic(): bool;
public function getName(): string;
/**
* @return \PHPStan\Reflection\ParameterReflection[]
*/
public function getParameters(): array;
public function isVariadic(): bool;
public function getReturnType(): Type;
}This is how you register the extension in project's PHPStan config file:
services: - class: App\PHPStan\EnumMethodsClassReflectionExtension tags: - phpstan.broker.methodsClassReflectionExtension
If the return type of a method is not always the same, but depends on an argument passed to the method, you can specify the return type by writing and registering an extension.
Because you have to write the code with the type-resolving logic, it can be as complex as you want.
After writing the sample extension, the variable $mergedArticle will have the correct type:
$mergedArticle = $this->entityManager->merge($article);
// $mergedArticle will have the same type as $articleThis is the interface for dynamic return type extension:
namespace PHPStan\Type;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
interface DynamicMethodReturnTypeExtension
{
public function getClass(): string;
public function isMethodSupported(MethodReflection $methodReflection): bool;
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type;
}And this is how you'd write the extension that correctly resolves the EntityManager::merge() return type:
public function getClass(): string
{
return \Doctrine\ORM\EntityManager::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'merge';
}
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
if (count($methodCall->args) === 0) {
return $methodReflection->getReturnType();
}
$arg = $methodCall->args[0]->value;
return $scope->getType($arg);
}And finally, register the extension to PHPStan in the project's config file:
services: - class: App\PHPStan\EntityManagerDynamicReturnTypeExtension tags: - phpstan.broker.dynamicMethodReturnTypeExtension
There's also an analogous functionality for:
This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.
Any contributions are welcome.
You can either run the whole build including linting and coding standards using
vendor/bin/phingor run only tests using
vendor/bin/phing tests| Back | FazBrowse Home | New Git URL |