Skip to content

Commit

Permalink
Refactor class to iterate over methods
Browse files Browse the repository at this point in the history
  • Loading branch information
shyim committed Jul 20, 2023
1 parent ea1b530 commit bc840d8
Showing 1 changed file with 21 additions and 33 deletions.
54 changes: 21 additions & 33 deletions src/Rule/ClassMethod/AddArgumentToClassWithoutDefaultRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,33 +65,37 @@ public function someMethod($value)
public function getNodeTypes(): array
{
return [
ClassMethod::class,
Class_::class,
];
}

/**
* @param ClassMethod $node
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
$hasChanged = false;

foreach ($this->configuration as $config) {
if (!$this->isObjectTypeMatch($node, $config->getObjectType())) {
continue;
foreach ($node as $method) {
if ($method instanceof ClassMethod) {
foreach ($this->configuration as $config) {
if (!$this->isObjectType($node, $config->getObjectType())) {
continue;
}
if (!$this->isName($method->name, $config->getMethod())) {
continue;
}

$param = new Param(new Variable($config->getName()));

if ($config->getType()) {
$param->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($config->getType(), TypeKind::PARAM);
}

$method->params[$config->getPosition()] = $param;
$hasChanged = true;
}
}
if (!$this->isName($node->name, $config->getMethod())) {
continue;
}

$param = new Param(new Variable($config->getName()));

if ($config->getType()) {
$param->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($config->getType(), TypeKind::PARAM);
}

$node->params[$config->getPosition()] = $param;
$hasChanged = true;
}

if ($hasChanged) {
Expand All @@ -108,20 +112,4 @@ public function configure(array $configuration): void
{
$this->configuration = $configuration;
}

private function isObjectTypeMatch(Node $node, ObjectType $objectType): bool
{
if ($node instanceof MethodCall) {
return $this->isObjectType($node->var, $objectType);
}
if ($node instanceof StaticCall) {
return $this->isObjectType($node->class, $objectType);
}
$classLike = $this->betterNodeFinder->findParentType($node, Class_::class);
if (!$classLike instanceof Class_) {
return false;
}

return $this->isObjectType($classLike, $objectType);
}
}

0 comments on commit bc840d8

Please sign in to comment.