use Dynamic AnnotationReplacerRector

This commit is contained in:
TomasVotruba 2018-02-09 01:14:45 +01:00
parent 6d6d99539d
commit 8853ac5957
4 changed files with 88 additions and 5 deletions

View File

@ -0,0 +1,72 @@
<?php declare(strict_types=1);
namespace Rector\Rector\Dynamic;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use Rector\Node\Attribute;
use Rector\Rector\AbstractPHPUnitRector;
use Rector\ReflectionDocBlock\NodeAnalyzer\DocBlockAnalyzer;
/**
* Before:
* - @scenario
*
* After:
* - @test
*/
final class AnnotationReplacerRector extends AbstractPHPUnitRector
{
/**
* @var string[][]
*/
private $classToAnnotationMap;
/**
* @var DocBlockAnalyzer
*/
private $docBlockAnalyzer;
/**
* @param string[][] $classToAnnotationMap
*/
public function __construct(array $classToAnnotationMap, DocBlockAnalyzer $docBlockAnalyzer)
{
$this->docBlockAnalyzer = $docBlockAnalyzer;
$this->classToAnnotationMap = $classToAnnotationMap;
}
public function isCandidate(Node $node): bool
{
if (! $node instanceof ClassMethod && ! $node instanceof Property) {
return false;
}
/** @var Node|null $parentNode */
$parentNode = $node->getAttribute(Attribute::PARENT_NODE);
if (! $parentNode) {
return false;
}
foreach ($this->classToAnnotationMap as $type => $annotationMap) {
if (! in_array($type, $parentNode->getAttribute(Attribute::TYPES), true)) {
continue;
}
return $this->docBlockAnalyzer->hasAnnotation($node, 'scenario');
}
return false;
}
/**
* @param ClassMethod|Property $classMethodOrPropertyNode
*/
public function refactor(Node $classMethodOrPropertyNode): ?Node
{
$this->docBlockAnalyzer->replaceAnnotationInNode($classMethodOrPropertyNode, 'scenario', 'test');
return $classMethodOrPropertyNode;
}
}

View File

@ -1,2 +1,4 @@
rectors:
Rector\Rector\Contrib\PHPUnit\ScenarioToTestAnnotationRector: ~
Rector\Rector\Dynamic\AnnotationReplacerRector:
PHPUnit\Framework\TestCase:
scenario: test

View File

@ -2,10 +2,10 @@
namespace Rector\Tests\Rector\Contrib\PHPUnit\ScenarioToTestAnnotationRector;
use Rector\Rector\Contrib\PHPUnit\ScenarioToTestAnnotationRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Rector\Rector\Dynamic\AnnotationReplacerRector;
use Rector\Testing\PHPUnit\AbstractConfigurableRectorTestCase;
final class ScenarioToTestAnnotationRectorTest extends AbstractRectorTestCase
final class ScenarioToTestAnnotationRectorTest extends AbstractConfigurableRectorTestCase
{
/**
* @dataProvider provideWrongToFixedFiles()
@ -30,6 +30,11 @@ final class ScenarioToTestAnnotationRectorTest extends AbstractRectorTestCase
*/
protected function getRectorClasses(): array
{
return [ScenarioToTestAnnotationRector::class];
return [AnnotationReplacerRector::class];
}
protected function provideConfig(): string
{
return __DIR__ . '/config/rector.yml';
}
}

View File

@ -0,0 +1,4 @@
rectors:
Rector\Rector\Dynamic\AnnotationReplacerRector:
PHPUnit\Framework\TestCase:
scenario: test