|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Classes; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Node\InClassNode; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use PHPStan\Type\ObjectType; |
| 11 | +use PHPStan\Type\VerbosityLevel; |
| 12 | +use function sprintf; |
| 13 | + |
| 14 | +/** |
| 15 | + * @implements Rule<InClassNode> |
| 16 | + */ |
| 17 | +class RequireExtendsRule implements Rule |
| 18 | +{ |
| 19 | + |
| 20 | + public function getNodeType(): string |
| 21 | + { |
| 22 | + return InClassNode::class; |
| 23 | + } |
| 24 | + |
| 25 | + public function processNode(Node $node, Scope $scope): array |
| 26 | + { |
| 27 | + $classReflection = $node->getClassReflection(); |
| 28 | + |
| 29 | + $errors = []; |
| 30 | + foreach ($classReflection->getImmediateInterfaces() as $interface) { |
| 31 | + $extendsTags = $interface->getRequireExtendsTags(); |
| 32 | + foreach ($extendsTags as $extendsTag) { |
| 33 | + $type = $extendsTag->getType(); |
| 34 | + if (!$type instanceof ObjectType) { |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + if ($classReflection->isSubclassOf($type->getClassName())) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + |
| 42 | + $errors[] = RuleErrorBuilder::message( |
| 43 | + sprintf( |
| 44 | + 'Interface %s requires implementing class to extend %s, but %s does not.', |
| 45 | + $interface->getDisplayName(), |
| 46 | + $type->describe(VerbosityLevel::typeOnly()), |
| 47 | + $classReflection->getDisplayName(), |
| 48 | + ), |
| 49 | + )->build(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + foreach ($classReflection->getTraits() as $trait) { |
| 54 | + $extendsTags = $trait->getRequireExtendsTags(); |
| 55 | + foreach ($extendsTags as $extendsTag) { |
| 56 | + $type = $extendsTag->getType(); |
| 57 | + if (!$type instanceof ObjectType) { |
| 58 | + continue; |
| 59 | + } |
| 60 | + |
| 61 | + if ($classReflection->isSubclassOf($type->getClassName())) { |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + $errors[] = RuleErrorBuilder::message( |
| 66 | + sprintf( |
| 67 | + 'Trait %s requires using class to extend %s, but %s does not.', |
| 68 | + $trait->getDisplayName(), |
| 69 | + $type->describe(VerbosityLevel::typeOnly()), |
| 70 | + $classReflection->getDisplayName(), |
| 71 | + ), |
| 72 | + )->build(); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return $errors; |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments