rector/rules/Php74/Rector/ArrayDimFetch/CurlyToSquareBracketArrayStringRector.php

70 lines
2.4 KiB
PHP
Raw Normal View History

<?php
declare (strict_types=1);
2022-06-06 16:43:29 +00:00
namespace RectorPrefix20220606\Rector\Php74\Rector\ArrayDimFetch;
2022-06-06 16:43:29 +00:00
use RectorPrefix20220606\PhpParser\Node;
use RectorPrefix20220606\PhpParser\Node\Expr\ArrayDimFetch;
use RectorPrefix20220606\Rector\Core\Rector\AbstractRector;
use RectorPrefix20220606\Rector\Core\ValueObject\PhpVersionFeature;
use RectorPrefix20220606\Rector\NodeTypeResolver\Node\AttributeKey;
use RectorPrefix20220606\Rector\Php74\Tokenizer\FollowedByCurlyBracketAnalyzer;
use RectorPrefix20220606\Rector\VersionBonding\Contract\MinPhpVersionInterface;
use RectorPrefix20220606\Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use RectorPrefix20220606\Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @changelog https://www.php.net/manual/en/migration74.deprecated.php
* @see \Rector\Tests\Php74\Rector\ArrayDimFetch\CurlyToSquareBracketArrayStringRector\CurlyToSquareBracketArrayStringRectorTest
*/
2022-06-06 16:43:29 +00:00
final class CurlyToSquareBracketArrayStringRector extends AbstractRector implements MinPhpVersionInterface
{
/**
* @readonly
* @var \Rector\Php74\Tokenizer\FollowedByCurlyBracketAnalyzer
*/
private $followedByCurlyBracketAnalyzer;
2022-06-06 16:43:29 +00:00
public function __construct(FollowedByCurlyBracketAnalyzer $followedByCurlyBracketAnalyzer)
{
$this->followedByCurlyBracketAnalyzer = $followedByCurlyBracketAnalyzer;
}
public function provideMinPhpVersion() : int
{
2022-06-06 16:43:29 +00:00
return PhpVersionFeature::DEPRECATE_CURLY_BRACKET_ARRAY_STRING;
}
2022-06-06 16:43:29 +00:00
public function getRuleDefinition() : RuleDefinition
{
2022-06-06 16:43:29 +00:00
return new RuleDefinition('Change curly based array and string to square bracket', [new CodeSample(<<<'CODE_SAMPLE'
$string = 'test';
echo $string{0};
$array = ['test'];
echo $array{0};
CODE_SAMPLE
, <<<'CODE_SAMPLE'
$string = 'test';
echo $string[0];
$array = ['test'];
echo $array[0];
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
2022-06-06 16:43:29 +00:00
return [ArrayDimFetch::class];
}
/**
* @param ArrayDimFetch $node
*/
2022-06-06 16:43:29 +00:00
public function refactor(Node $node) : ?Node
{
if (!$this->followedByCurlyBracketAnalyzer->isFollowed($this->file, $node)) {
return null;
}
// re-draw the ArrayDimFetch to use [] bracket
2022-06-06 16:43:29 +00:00
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
return $node;
}
}