[Symfony] add FormIsValidRector

This commit is contained in:
TomasVotruba 2017-09-01 15:04:36 +02:00
parent 5bbc0443fa
commit 9f5e26f7e6
5 changed files with 111 additions and 0 deletions

View File

@ -45,6 +45,7 @@ parameters:
# classes might not exist
- */src/Rector/Contrib/Nette/*Rector.php
- src/Rector/Contrib/Symfony/StringFormTypeToClassRector.php
- src/Rector/Contrib/Symfony/FormIsValidRector.php
Symplify\CodingStandard\Sniffs\Debug\CommentedOutCodeSniff:
# examples of code to be found
- src/Rector/Contrib/Symfony/GetterToPropertyRector.php

View File

@ -0,0 +1,71 @@
<?php declare(strict_types=1);
namespace Rector\Rector\Contrib\Symfony;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use Rector\Deprecation\SetNames;
use Rector\Rector\AbstractRector;
/**
* Converts all:
* $form->isValid()
*
* into:
* $form->isSubmitted() && $form->isValid()
*/
final class FormIsValidRector extends AbstractRector
{
public function getSetName(): string
{
return SetNames::SYMFONY;
}
public function sinceVersion(): float
{
return 4.0;
}
public function isCandidate(Node $node): bool
{
if (! $node instanceof MethodCall) {
return false;
}
if ($node->var->getAttribute('type') !== 'Symfony\Component\Form\Form') {
return false;
}
if ((string) $node->name !== 'isValid') {
return false;
}
if ($node->getAttribute('prev') !== null) {
return false;
}
return true;
}
/**
* @param MethodCall $node
*/
public function refactor(Node $node): ?Node
{
$varName = $node->var->name;
return new BooleanAnd(
$this->createMethodCall($varName, 'isSubmitted'),
$this->createMethodCall($varName, 'isValid')
);
}
private function createMethodCall(string $varName, string $methodName): MethodCall
{
$varNode = new Variable($varName);
return new MethodCall($varNode, $methodName);
}
}

View File

@ -0,0 +1,7 @@
<?php declare (strict_types=1);
$form = new \Symfony\Component\Form\Form;
if ($form->isSubmitted() && $form->isValid()) {
$this->processForm($form);
}

View File

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
namespace Rector\Tests\Rector\Contrib\Symfony\FormIsValidRector;
use Rector\Rector\Contrib\Symfony\FormIsValidRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
final class Test extends AbstractRectorTestCase
{
public function test(): void
{
$this->doTestFileMatchesExpectedContent(
__DIR__ . '/Wrong/wrong.php.inc',
__DIR__ . '/Correct/correct.php.inc'
);
}
/**
* @return string[]
*/
protected function getRectorClasses(): array
{
return [FormIsValidRector::class];
}
}

View File

@ -0,0 +1,7 @@
<?php declare (strict_types=1);
$form = new \Symfony\Component\Form\Form;
if ($form->isValid()) {
$this->processForm($form);
}