rector/rules/generic/src/Rector/FuncCall/RemoveFuncCallArgRector.php

87 lines
2.4 KiB
PHP
Raw Normal View History

2020-05-31 14:19:58 +00:00
<?php
declare(strict_types=1);
namespace Rector\Generic\Rector\FuncCall;
2020-05-31 14:19:58 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
2020-07-29 23:39:41 +00:00
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
2020-05-31 14:19:58 +00:00
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\ConfiguredCodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
use Rector\Generic\ValueObject\RemovedFunctionArgument;
use Webmozart\Assert\Assert;
2020-05-31 14:19:58 +00:00
/**
2020-06-17 12:16:17 +00:00
* @sponsor Thanks https://twitter.com/afilina & Zenika (CAN) for sponsoring this rule - visit them on https://zenika.ca/en/en
2020-05-31 14:19:58 +00:00
*
* @see \Rector\Generic\Tests\Rector\FuncCall\RemoveFuncCallArgRector\RemoveFuncCallArgRectorTest
2020-05-31 14:19:58 +00:00
*/
2020-07-29 23:39:41 +00:00
final class RemoveFuncCallArgRector extends AbstractRector implements ConfigurableRectorInterface
2020-05-31 14:19:58 +00:00
{
/**
2020-07-29 23:39:41 +00:00
* @var string
2020-05-31 14:19:58 +00:00
*/
public const REMOVED_FUNCTION_ARGUMENTS = 'removed_function_arguments';
2020-05-31 14:19:58 +00:00
/**
* @var RemovedFunctionArgument[]
2020-05-31 14:19:58 +00:00
*/
private $removedFunctionArguments = [];
2020-05-31 14:19:58 +00:00
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Remove argument by position by function name', [
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
remove_last_arg(1, 2);
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
remove_last_arg(1);
CODE_SAMPLE
, [
self::REMOVED_FUNCTION_ARGUMENTS => [new RemovedFunctionArgument('remove_last_arg', 1)],
2020-05-31 14:19:58 +00:00
]),
]);
}
/**
* @return string[]
2020-05-31 14:19:58 +00:00
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->removedFunctionArguments as $removedFunctionArgument) {
if (! $this->isName($node->name, $removedFunctionArgument->getFunction())) {
2020-05-31 14:19:58 +00:00
continue;
}
foreach (array_keys($node->args) as $position) {
if ($removedFunctionArgument->getArgumentPosition() !== $position) {
2020-05-31 14:19:58 +00:00
continue;
}
unset($node->args[$position]);
}
}
return $node;
}
2020-07-29 23:39:41 +00:00
public function configure(array $configuration): void
{
$removedFunctionArguments = $configuration[self::REMOVED_FUNCTION_ARGUMENTS] ?? [];
Assert::allIsInstanceOf($removedFunctionArguments, RemovedFunctionArgument::class);
$this->removedFunctionArguments = $removedFunctionArguments;
2020-07-29 23:39:41 +00:00
}
2020-05-31 14:19:58 +00:00
}