rector/rules/php80/src/Rector/Identical/StrStartsWithRector.php

94 lines
2.4 KiB
PHP
Raw Normal View History

2020-04-23 12:34:27 +00:00
<?php
declare(strict_types=1);
namespace Rector\Php80\Rector\Identical;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
2020-04-23 21:49:56 +00:00
use Rector\Php80\Contract\StrStartWithMatchAndRefactorInterface;
2020-04-23 12:34:27 +00:00
/**
* @see https://wiki.php.net/rfc/add_str_starts_with_and_ends_with_functions
*
* @see https://3v4l.org/RQHB5 for weak compare
* @see https://3v4l.org/AmLja for weak compare
*
* @see \Rector\Php80\Tests\Rector\Identical\StrStartsWithRector\StrStartsWithRectorTest
*/
final class StrStartsWithRector extends AbstractRector
{
/**
2020-04-23 21:49:56 +00:00
* @var StrStartWithMatchAndRefactorInterface[]
2020-04-23 12:34:27 +00:00
*/
2020-04-23 21:49:56 +00:00
private $strStartWithMatchAndRefactors = [];
2020-04-23 12:34:27 +00:00
/**
2020-04-23 21:49:56 +00:00
* @param StrStartWithMatchAndRefactorInterface[] $strStartWithMatchAndRefactors
2020-04-23 12:34:27 +00:00
*/
2020-04-23 21:49:56 +00:00
public function __construct(array $strStartWithMatchAndRefactors)
{
$this->strStartWithMatchAndRefactors = $strStartWithMatchAndRefactors;
2020-04-23 12:34:27 +00:00
}
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Change helper functions to str_starts_with()', [
new CodeSample(
<<<'PHP'
class SomeClass
{
public function run()
{
$isMatch = substr($haystack, 0, strlen($needle)) === $needle;
$isNotMatch = substr($haystack, 0, strlen($needle)) !== $needle;
}
}
PHP
,
<<<'PHP'
class SomeClass
{
public function run()
{
$isMatch = str_starts_with($haystack, $needle);
$isNotMatch = ! str_starts_with($haystack, $needle);
2020-04-23 12:34:27 +00:00
}
}
PHP
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [Identical::class, NotIdentical::class];
}
/**
* @param Identical|NotIdentical $node
*/
public function refactor(Node $node): ?Node
{
2020-04-23 21:49:56 +00:00
foreach ($this->strStartWithMatchAndRefactors as $strStartWithMatchAndRefactor) {
$strStartsWithValueObject = $strStartWithMatchAndRefactor->match($node);
if ($strStartsWithValueObject === null) {
continue;
}
2020-04-23 12:34:27 +00:00
return $strStartWithMatchAndRefactor->refactorStrStartsWith($strStartsWithValueObject);
2020-04-23 12:34:27 +00:00
}
2020-07-01 21:35:40 +00:00
return null;
2020-04-23 12:34:27 +00:00
}
}