[CodeQuality] Add AddPregQuoteDelimiterRector

This commit is contained in:
Tomas Votruba 2019-10-17 18:42:48 +02:00
parent 197efa188c
commit 42e4454b48
5 changed files with 142 additions and 0 deletions

View File

@ -43,3 +43,4 @@ services:
Rector\CodeQuality\Rector\FuncCall\RemoveSoleValueSprintfRector: ~
Rector\CodeQuality\Rector\If_\ShortenElseIfRector: ~
Rector\SOLID\Rector\ClassMethod\UseInterfaceOverImplementationInConstructorRector: ~
Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector: ~

View File

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\FuncCall;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
/**
* @see \Rector\CodeQuality\Tests\Rector\FuncCall\AddPregQuoteDelimiterRector\AddPregQuoteDelimiterRectorTest
*/
final class AddPregQuoteDelimiterRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Add preg_quote delimiter when missing', [
new CodeSample(
<<<'PHP'
class SomeClass
{
public function test()
{
return preg_quote('name');
}
}
PHP
,
<<<'PHP'
class SomeClass
{
public function test()
{
return preg_quote('name', '#');
}
}
PHP
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isName($node, 'preg_quote')) {
return null;
}
// already completed
if (isset($node->args[1])) {
return null;
}
$node->args[1] = new Node\Arg(new Node\Scalar\String_('#'));
return $node;
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Tests\Rector\FuncCall\AddPregQuoteDelimiterRector;
use Iterator;
use Rector\CodeQuality\Rector\FuncCall\AddPregQuoteDelimiterRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
final class AddPregQuoteDelimiterRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideDataForTest()
*/
public function test(string $file): void
{
$this->doTestFile($file);
}
public function provideDataForTest(): Iterator
{
yield [__DIR__ . '/Fixture/fixture.php.inc'];
yield [__DIR__ . '/Fixture/skip.php.inc'];
}
protected function getRectorClass(): string
{
return AddPregQuoteDelimiterRector::class;
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace Rector\CodeQuality\Tests\Rector\FuncCall\AddPregQuoteDelimiterRector\Fixture;
class SomeClass
{
public function test()
{
return preg_quote('name');
}
}
?>
-----
<?php
namespace Rector\CodeQuality\Tests\Rector\FuncCall\AddPregQuoteDelimiterRector\Fixture;
class SomeClass
{
public function test()
{
return preg_quote('name', '#');
}
}
?>

View File

@ -0,0 +1,11 @@
<?php
namespace Rector\CodeQuality\Tests\Rector\FuncCall\AddPregQuoteDelimiterRector\Fixture;
class Skip
{
public function test()
{
return preg_quote('name', '_');
}
}