|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Cast; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\Cast; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\DependencyInjection\RegisteredRule; |
| 9 | +use PHPStan\Php\PhpVersion; |
| 10 | +use PHPStan\Rules\Rule; |
| 11 | +use PHPStan\Rules\RuleErrorBuilder; |
| 12 | + |
| 13 | +/** |
| 14 | + * @implements Rule<Cast> |
| 15 | + */ |
| 16 | +#[RegisteredRule(level: 0)] |
| 17 | +final class DeprecatedCastRule implements Rule |
| 18 | +{ |
| 19 | + |
| 20 | + public function __construct(private PhpVersion $phpVersion) |
| 21 | + { |
| 22 | + } |
| 23 | + |
| 24 | + public function getNodeType(): string |
| 25 | + { |
| 26 | + return Cast::class; |
| 27 | + } |
| 28 | + |
| 29 | + public function processNode(Node $node, Scope $scope): array |
| 30 | + { |
| 31 | + if (!$this->phpVersion->deprecatesNonStandardCasts()) { |
| 32 | + return []; |
| 33 | + } |
| 34 | + |
| 35 | + if ($node instanceof Cast\Int_) { |
| 36 | + $kind = $node->getAttribute('kind', Cast\Int_::KIND_INT); |
| 37 | + if ($kind === Cast\Int_::KIND_INTEGER) { |
| 38 | + return [ |
| 39 | + RuleErrorBuilder::message('Non-standard (integer) cast is deprecated in PHP 8.5. Use (int) instead.') |
| 40 | + ->identifier('cast.deprecated') |
| 41 | + ->build(), |
| 42 | + ]; |
| 43 | + } |
| 44 | + |
| 45 | + return []; |
| 46 | + } |
| 47 | + |
| 48 | + if ($node instanceof Cast\Bool_) { |
| 49 | + $kind = $node->getAttribute('kind', Cast\Bool_::KIND_BOOL); |
| 50 | + if ($kind === Cast\Bool_::KIND_BOOLEAN) { |
| 51 | + return [ |
| 52 | + RuleErrorBuilder::message('Non-standard (boolean) cast is deprecated in PHP 8.5. Use (bool) instead.') |
| 53 | + ->identifier('cast.deprecated') |
| 54 | + ->build(), |
| 55 | + ]; |
| 56 | + } |
| 57 | + |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + if ($node instanceof Cast\Double) { |
| 62 | + $kind = $node->getAttribute('kind', Cast\Double::KIND_FLOAT); |
| 63 | + if ($kind === Cast\Double::KIND_DOUBLE) { |
| 64 | + return [ |
| 65 | + RuleErrorBuilder::message('Non-standard (double) cast is deprecated in PHP 8.5. Use (float) instead.') |
| 66 | + ->identifier('cast.deprecated') |
| 67 | + ->build(), |
| 68 | + ]; |
| 69 | + } |
| 70 | + |
| 71 | + return []; |
| 72 | + } |
| 73 | + |
| 74 | + if ($node instanceof Cast\String_) { |
| 75 | + $kind = $node->getAttribute('kind', Cast\String_::KIND_STRING); |
| 76 | + if ($kind === Cast\String_::KIND_BINARY) { |
| 77 | + return [ |
| 78 | + RuleErrorBuilder::message('Non-standard (binary) cast is deprecated in PHP 8.5. Use (string) instead.') |
| 79 | + ->identifier('cast.deprecated') |
| 80 | + ->build(), |
| 81 | + ]; |
| 82 | + } |
| 83 | + |
| 84 | + return []; |
| 85 | + } |
| 86 | + |
| 87 | + return []; |
| 88 | + } |
| 89 | + |
| 90 | +} |
0 commit comments