|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Nette\PHPStan\Php; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PHPStan\Analyser\Error; |
| 9 | +use PHPStan\Analyser\IgnoreErrorExtension; |
| 10 | +use PHPStan\Analyser\Scope; |
| 11 | +use function str_contains, substr_count; |
| 12 | + |
| 13 | + |
| 14 | +/** |
| 15 | + * Suppresses 'argument.type' when an arrow function (which always returns a value) is passed |
| 16 | + * to a parameter typed as Closure(): void. The list of affected functions/methods is configurable. |
| 17 | + */ |
| 18 | +class ArrowFunctionVoidIgnoreExtension implements IgnoreErrorExtension |
| 19 | +{ |
| 20 | + /** @var list<string> */ |
| 21 | + private array $functions = []; |
| 22 | + |
| 23 | + /** @var list<string> */ |
| 24 | + private array $methods = []; |
| 25 | + |
| 26 | + |
| 27 | + /** @param list<string> $items plain names for functions, Class::method for methods */ |
| 28 | + public function __construct(array $items) |
| 29 | + { |
| 30 | + foreach ($items as $item) { |
| 31 | + if (str_contains($item, '::')) { |
| 32 | + $this->methods[] = $item; |
| 33 | + } else { |
| 34 | + $this->functions[] = $item; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + public function shouldIgnore(Error $error, Node $node, Scope $scope): bool |
| 41 | + { |
| 42 | + if ($error->getIdentifier() !== 'argument.type') { |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + $message = $error->getMessage(); |
| 47 | + |
| 48 | + if (!str_contains($message, 'Closure(): void')) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + if (substr_count($message, 'Closure(') < 2) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + foreach ($this->functions as $function) { |
| 57 | + if (str_contains($message, "function $function(")) { |
| 58 | + return true; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + foreach ($this->methods as $method) { |
| 63 | + if (str_contains($message, "$method(")) { |
| 64 | + return true; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | +} |
0 commit comments