|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Deprecations; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Stmt\ClassConst; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use function sprintf; |
| 11 | + |
| 12 | +/** |
| 13 | + * @implements Rule<ClassConst> |
| 14 | + */ |
| 15 | +class OverrideDeprecatedConstantRule implements Rule |
| 16 | +{ |
| 17 | + |
| 18 | + /** @var DeprecatedScopeHelper */ |
| 19 | + private $deprecatedScopeHelper; |
| 20 | + |
| 21 | + public function __construct(DeprecatedScopeHelper $deprecatedScopeHelper) |
| 22 | + { |
| 23 | + $this->deprecatedScopeHelper = $deprecatedScopeHelper; |
| 24 | + } |
| 25 | + |
| 26 | + public function getNodeType(): string |
| 27 | + { |
| 28 | + return ClassConst::class; |
| 29 | + } |
| 30 | + |
| 31 | + public function processNode(Node $node, Scope $scope): array |
| 32 | + { |
| 33 | + if ($this->deprecatedScopeHelper->isScopeDeprecated($scope)) { |
| 34 | + return []; |
| 35 | + } |
| 36 | + |
| 37 | + if (!$scope->isInClass()) { |
| 38 | + return []; |
| 39 | + } |
| 40 | + |
| 41 | + if ($node->isPrivate()) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + $class = $scope->getClassReflection(); |
| 46 | + |
| 47 | + $parents = $class->getParents(); |
| 48 | + |
| 49 | + $name = (string) $node->consts[0]->name; |
| 50 | + |
| 51 | + foreach ($parents as $parent) { |
| 52 | + if (!$parent->hasConstant($name)) { |
| 53 | + continue; |
| 54 | + } |
| 55 | + |
| 56 | + $parentConst = $parent->getConstant($name); |
| 57 | + |
| 58 | + if (!$parentConst->isDeprecated()->yes()) { |
| 59 | + return []; |
| 60 | + } |
| 61 | + |
| 62 | + return [RuleErrorBuilder::message(sprintf( |
| 63 | + 'Class %s overrides deprecated const %s of class %s.', |
| 64 | + $class->getName(), |
| 65 | + $name, |
| 66 | + $parent->getName() |
| 67 | + ))->identifier('constant.deprecated')->build()]; |
| 68 | + } |
| 69 | + |
| 70 | + return []; |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments