|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\PhpDoc; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Node\VarTagUsagesNode; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\Rules\RuleErrorBuilder; |
| 10 | +use PHPStan\Rules\RuleLevelHelper; |
| 11 | +use PHPStan\Type\Type; |
| 12 | +use PHPStan\Type\TypeCombinator; |
| 13 | +use PHPStan\Type\TypeUtils; |
| 14 | +use PHPStan\Type\VerbosityLevel; |
| 15 | +use function sprintf; |
| 16 | + |
| 17 | +/** |
| 18 | + * A `@var` tag over `$x = null`, `$x = []`, a scalar, a `new` of a generic |
| 19 | + * class or `static $x` declares what the variable holds in the rest of the |
| 20 | + * function. A write that makes the variable hold something the tag does not |
| 21 | + * accept - `$x[] = <element of another type>`, `$x .= ...`, `$x++` - and a |
| 22 | + * template argument the body infers differently are reported. |
| 23 | + * |
| 24 | + * @implements Rule<VarTagUsagesNode> |
| 25 | + */ |
| 26 | +final class VarTagReflectsUsagesRule implements Rule |
| 27 | +{ |
| 28 | + |
| 29 | + public function __construct(private RuleLevelHelper $ruleLevelHelper) |
| 30 | + { |
| 31 | + } |
| 32 | + |
| 33 | + public function getNodeType(): string |
| 34 | + { |
| 35 | + return VarTagUsagesNode::class; |
| 36 | + } |
| 37 | + |
| 38 | + public function processNode(Node $node, Scope $scope): array |
| 39 | + { |
| 40 | + $varTagType = $node->getVarTagType(); |
| 41 | + $rejected = $this->getRejectedTypes($varTagType, $node->getAssignedType()); |
| 42 | + // a tag more precise than the generalized inferred template arguments |
| 43 | + // (Collection<true>) is fine when it accepts the precise ones |
| 44 | + if ($rejected === [] || $this->getRejectedTypes($varTagType, $node->getPreciseAssignedType()) === []) { |
| 45 | + return []; |
| 46 | + } |
| 47 | + $usagesType = TypeCombinator::union(...$rejected); |
| 48 | + |
| 49 | + $verbosity = VerbosityLevel::getRecommendedLevelByType($varTagType, $usagesType); |
| 50 | + |
| 51 | + return [ |
| 52 | + RuleErrorBuilder::message(sprintf( |
| 53 | + 'PHPDoc tag @var with type %s does not accept type %s assigned to $%s.', |
| 54 | + $varTagType->describe($verbosity), |
| 55 | + $usagesType->describe($verbosity), |
| 56 | + $node->getVariableName(), |
| 57 | + ))->identifier('varTag.usages')->build(), |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @return list<Type> |
| 63 | + */ |
| 64 | + private function getRejectedTypes(Type $varTagType, Type $assignedType): array |
| 65 | + { |
| 66 | + $rejected = []; |
| 67 | + foreach (TypeUtils::flattenTypes($assignedType) as $type) { |
| 68 | + if ($this->ruleLevelHelper->isSuperTypeOf($varTagType, $type)->result) { |
| 69 | + continue; |
| 70 | + } |
| 71 | + $rejected[] = $type; |
| 72 | + } |
| 73 | + |
| 74 | + return $rejected; |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments