|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Properties; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Node\ClassPropertyNode; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use PHPStan\Type\CallableType; |
| 11 | +use PHPStan\Type\IntersectionType; |
| 12 | +use PHPStan\Type\Type; |
| 13 | +use PHPStan\Type\TypeTraverser; |
| 14 | +use PHPStan\Type\UnionType; |
| 15 | +use function sprintf; |
| 16 | + |
| 17 | +/** |
| 18 | + * @implements Rule<ClassPropertyNode> |
| 19 | + */ |
| 20 | +class InvalidCallablePropertyTypeRule implements Rule |
| 21 | +{ |
| 22 | + |
| 23 | + public function getNodeType(): string |
| 24 | + { |
| 25 | + return ClassPropertyNode::class; |
| 26 | + } |
| 27 | + |
| 28 | + public function processNode(Node $node, Scope $scope): array |
| 29 | + { |
| 30 | + $classReflection = $node->getClassReflection(); |
| 31 | + $propertyReflection = $classReflection->getNativeProperty($node->getName()); |
| 32 | + |
| 33 | + if (!$propertyReflection->hasNativeType()) { |
| 34 | + return []; |
| 35 | + } |
| 36 | + |
| 37 | + $nativeType = $propertyReflection->getNativeType(); |
| 38 | + $callableTypes = []; |
| 39 | + |
| 40 | + TypeTraverser::map($nativeType, static function (Type $type, callable $traverse) use (&$callableTypes): Type { |
| 41 | + if ($type instanceof UnionType || $type instanceof IntersectionType) { |
| 42 | + return $traverse($type); |
| 43 | + } |
| 44 | + |
| 45 | + if ($type instanceof CallableType) { |
| 46 | + $callableTypes[] = $type; |
| 47 | + } |
| 48 | + |
| 49 | + return $type; |
| 50 | + }); |
| 51 | + |
| 52 | + if ($callableTypes === []) { |
| 53 | + return []; |
| 54 | + } |
| 55 | + |
| 56 | + return [ |
| 57 | + RuleErrorBuilder::message(sprintf( |
| 58 | + 'Property %s::$%s cannot have callable in its type declaration.', |
| 59 | + $classReflection->getDisplayName(), |
| 60 | + $node->getName(), |
| 61 | + ))->identifier('property.callableType')->nonIgnorable()->build(), |
| 62 | + ]; |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments