Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
/**
* @param-out int $count
* @pure-unless-parameter-passed $count
*/
function myReplace(string $subject, int &$count): string // ERROR: Function myReplace() is marked @pure-unless-parameter-passed for parameter $count, but $count is not optional, so function myReplace() is never pure.
{
$count = 1;
return $subject;
}
Why is it reported? #
The @pure-unless-parameter-passed tag marks a function as pure unless an argument is passed for the named by-reference parameter. It describes functions like preg_replace() or str_replace(), whose optional $count out-parameter is the only thing that makes a call impure: calls that omit it are pure, calls that pass it write into the caller’s variable.
Here $count has no default value, so every call has to pass it. The condition under which the function would be pure can never be met, which makes the tag meaningless — the function is effectively always impure.
How to fix it #
Make the parameter optional by giving it a default value, so callers can omit it and get a pure call:
/**
* @param-out int $count
* @pure-unless-parameter-passed $count
*/
-function myReplace(string $subject, int &$count): string
+function myReplace(string $subject, int &$count = 0): string
{
$count = 1;
return $subject;
}
If the parameter has to stay required, the function is never pure. Remove the tag:
/**
* @param-out int $count
- * @pure-unless-parameter-passed $count
*/
function myReplace(string $subject, int &$count): string
How to ignore this error #
You can use the identifier pureFunction.nonOptionalParameterPassed to ignore this error using a comment:
// @phpstan-ignore pureFunction.nonOptionalParameterPassed
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: pureFunction.nonOptionalParameterPassed