I have a function that had the #[Pure]
attribute, but after I changed the function to use array_map
in it, PhpStorm complains that the "Method might produce side effects". I also see that array_map
is not marked as #[Pure]
and I assume this has to do with the fact that you can’t make assumptions about the callback. My callback in this case should be pure since it just calls a pure method.
Is there a way to let the IDE know that this array_map
is pure, or is there a way I should annotate my callback function?
This is the code:
/**
* @param array $msgArr
* @return int
*/
#[Pure] <== this one complains
public function getHighestNumericalCodeFromMessageArray(array $msgArr): int
{
$numericalCodeArr = array_map(fn($msg) => $this->getNumericalCodeFromMessage($msg) % 99, $msgArr);
return max($numericalCodeArr);
}
/**
* @param string $msg
* @return int
*/
#[Pure]
public function getNumericalCodeFromMessage(string $msg): int
{
$trimmedMsg = trim($msg);
if (is_numeric($trimmedMsg)) return (int)$trimmedMsg;
$code = array_search($trimmedMsg, self::AVAILABILITY_MESSAGES, false);
return $code !== false ? (int)$code : 0;
}
EDIT: I had also tried giving the lambda function the #[Pure]
attribute as also suggested by Kumara, but this did not remove the warning.
2
Answers
Try and inform the IDE that the lambda function inside array_map is pure, you can explicitly annotate the lambda function with the #[Pure] attribute as well. But not sure whether, PHPStorm will fully support this attribute for lambdas, but you can try the following approach:
In this example, we declare a /** @var callable $pureCallback */ annotation comment to inform PhpStorm that the lambda function assigned to $pureCallback is a callable and considered pure. This should suppress the warning in PhpStorm regarding the lambda function’s purity.
However, keep in mind that this is a workaround, and it’s important to document the code well so that others who work with it understand the intent. PhpStorm’s static analysis capabilities are limited compared to languages with stronger type systems, so sometimes you need to provide these hints to help the IDE understand your code better.