|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\Php85\Rector\FuncCall; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\FuncCall; |
| 9 | +use PhpParser\Node\Scalar\Int_; |
| 10 | +use PhpParser\Node\Scalar\String_; |
| 11 | +use Rector\PhpParser\Node\Value\ValueResolver; |
| 12 | +use Rector\Rector\AbstractRector; |
| 13 | +use Rector\ValueObject\PhpVersionFeature; |
| 14 | +use Rector\VersionBonding\Contract\MinPhpVersionInterface; |
| 15 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 16 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 17 | + |
| 18 | +/** |
| 19 | + * @see https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_passing_string_which_are_not_one_byte_long_to_ord |
| 20 | + * @see \Rector\Tests\Php85\Rector\FuncCall\OrdSingleByteRector\OrdSingleByteRectorTest |
| 21 | + */ |
| 22 | +final class OrdSingleByteRector extends AbstractRector implements MinPhpVersionInterface |
| 23 | +{ |
| 24 | + public function __construct( |
| 25 | + private readonly ValueResolver $valueResolver |
| 26 | + ) { |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + public function getRuleDefinition(): RuleDefinition |
| 31 | + { |
| 32 | + return new RuleDefinition( |
| 33 | + 'Replace ord($str) with ord($str[0])', |
| 34 | + [ |
| 35 | + new CodeSample( |
| 36 | + <<<'CODE_SAMPLE' |
| 37 | +echo ord('abc'); |
| 38 | +CODE_SAMPLE |
| 39 | + , |
| 40 | + <<<'CODE_SAMPLE' |
| 41 | +echo ord('a'); |
| 42 | +CODE_SAMPLE |
| 43 | + ), |
| 44 | + ] |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + public function getNodeTypes(): array |
| 49 | + { |
| 50 | + return [FuncCall::class]; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param FuncCall $node |
| 55 | + */ |
| 56 | + public function refactor(Node $node): ?Node |
| 57 | + { |
| 58 | + if ($node->isFirstClassCallable()) { |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + if (! $this->isName($node, 'ord')) { |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + $args = $node->getArgs(); |
| 67 | + |
| 68 | + if (! isset($node->args[0])) { |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | + $argExpr = $args[0]->value; |
| 73 | + |
| 74 | + $value = $this->valueResolver->getValue($argExpr); |
| 75 | + |
| 76 | + if ($value === null) { |
| 77 | + return null; |
| 78 | + } |
| 79 | + |
| 80 | + $isInt = is_int($value); |
| 81 | + $value = (string) $value; |
| 82 | + $byte = $value[0] ?? ''; |
| 83 | + |
| 84 | + $byteValue = $isInt ? new Int_((int) $byte) : new String_($byte); |
| 85 | + |
| 86 | + $args[0]->value = $byteValue; |
| 87 | + $node->args = $args; |
| 88 | + |
| 89 | + return $node; |
| 90 | + } |
| 91 | + |
| 92 | + public function provideMinPhpVersion(): int |
| 93 | + { |
| 94 | + return PhpVersionFeature::DEPRECATE_ORD_WITH_MULTIBYTE_STRING; |
| 95 | + } |
| 96 | +} |
0 commit comments