rector/rules/php72/src/Rector/FuncCall/ParseStrWithResultArgumentRector.php

86 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
2018-12-15 11:34:42 +00:00
namespace Rector\Php72\Rector\FuncCall;
2018-12-15 11:34:42 +00:00
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
use Rector\NodeTypeResolver\Node\AttributeKey;
2018-12-15 11:34:42 +00:00
/**
* @see https://3v4l.org/u5pes
* @see https://github.com/gueff/blogimus/commit/04086a10320595470efe446c7ddd90e602aa7228
* @see https://github.com/pxgamer/youtube-dl-php/commit/83cb32b8b36844f2e39f82a862a5ab73da77b608
* @see \Rector\Php72\Tests\Rector\FuncCall\ParseStrWithResultArgumentRector\ParseStrWithResultArgumentRectorTest
2018-12-15 11:34:42 +00:00
*/
final class ParseStrWithResultArgumentRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Use $result argument in parse_str() function', [
new CodeSample(
2019-09-18 06:14:35 +00:00
<<<'PHP'
2018-12-15 11:34:42 +00:00
parse_str($this->query);
$data = get_defined_vars();
2019-09-18 06:14:35 +00:00
PHP
2018-12-15 11:34:42 +00:00
,
2019-09-18 06:14:35 +00:00
<<<'PHP'
2018-12-15 11:34:42 +00:00
parse_str($this->query, $result);
$data = $result;
2019-09-18 06:14:35 +00:00
PHP
2018-12-15 11:34:42 +00:00
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isName($node, 'parse_str')) {
return null;
}
if (isset($node->args[1])) {
return null;
}
2018-12-15 11:34:42 +00:00
$resultVariable = new Variable('result');
$node->args[1] = new Arg($resultVariable);
$expression = $node->getAttribute(AttributeKey::CURRENT_STATEMENT);
2019-01-25 00:49:26 +00:00
if ($expression === null) {
return null;
}
$nextExpression = $expression->getAttribute(AttributeKey::NEXT_NODE);
2019-01-25 00:49:26 +00:00
if ($nextExpression === null) {
return null;
}
2018-12-15 11:34:42 +00:00
$this->traverseNodesWithCallable($nextExpression, function (Node $node) use ($resultVariable): ?Variable {
2020-02-29 23:06:45 +00:00
if ($this->isFuncCallName($node, 'get_defined_vars')) {
return $resultVariable;
2018-12-15 11:34:42 +00:00
}
return null;
});
return $node;
}
}