rector/rules/Transform/Rector/Assign/PropertyAssignToMethodCallR...

75 lines
2.6 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Transform\Rector\Assign;
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\Rector\AbstractRector;
use Rector\Transform\ValueObject\PropertyAssignToMethodCall;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix202403\Webmozart\Assert\Assert;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Transform\Rector\Assign\PropertyAssignToMethodCallRector\PropertyAssignToMethodCallRectorTest
2019-09-03 09:11:45 +00:00
*/
final class PropertyAssignToMethodCallRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var PropertyAssignToMethodCall[]
*/
private $propertyAssignsToMethodCalls = [];
public function getRuleDefinition() : RuleDefinition
2018-04-07 23:35:59 +00:00
{
return new RuleDefinition('Turns property assign of specific type and property name to method call', [new ConfiguredCodeSample(<<<'CODE_SAMPLE'
$someObject = new SomeClass;
2018-08-01 16:15:06 +00:00
$someObject->oldProperty = false;
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2018-08-01 16:15:06 +00:00
$someObject = new SomeClass;
$someObject->newMethodCall(false);
CODE_SAMPLE
, [new PropertyAssignToMethodCall('SomeClass', 'oldProperty', 'newMethodCall')])]);
2018-04-07 23:35:59 +00:00
}
2018-08-14 22:12:41 +00:00
/**
* @return array<class-string<Node>>
2018-08-14 22:12:41 +00:00
*/
public function getNodeTypes() : array
{
return [Assign::class];
}
/**
* @param Assign $node
*/
public function refactor(Node $node) : ?Node
{
if (!$node->var instanceof PropertyFetch) {
return null;
}
$propertyFetchNode = $node->var;
2017-11-06 13:15:35 +00:00
/** @var Variable $propertyNode */
2017-11-06 11:48:43 +00:00
$propertyNode = $propertyFetchNode->var;
foreach ($this->propertyAssignsToMethodCalls as $propertyAssignToMethodCall) {
if (!$this->isName($propertyFetchNode, $propertyAssignToMethodCall->getOldPropertyName())) {
continue;
}
if (!$this->isObjectType($propertyFetchNode->var, $propertyAssignToMethodCall->getObjectType())) {
continue;
}
return $this->nodeFactory->createMethodCall($propertyNode, $propertyAssignToMethodCall->getNewMethodName(), [$node->expr]);
}
return null;
}
/**
* @param mixed[] $configuration
*/
public function configure(array $configuration) : void
2020-07-29 23:39:41 +00:00
{
Assert::allIsAOf($configuration, PropertyAssignToMethodCall::class);
$this->propertyAssignsToMethodCalls = $configuration;
2020-07-29 23:39:41 +00:00
}
}