Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions src/NodeManipulator/ClassDependencyManipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

namespace Rector\NodeManipulator;

use PhpParser\Modifiers;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
Expand Down Expand Up @@ -248,13 +250,31 @@ private function addPromotedProperty(
$param = $this->nodeFactory->createPromotedPropertyParam($propertyMetadata);

if ($constructClassMethod instanceof ClassMethod) {
// parameter is already added
if ($this->hasMethodParameter($constructClassMethod, $propertyMetadata->getName())) {
$hasOwnConstruct = $class->getMethod(MethodName::CONSTRUCT) instanceof ClassMethod;
$matchedParam = $this->matchMethodParameter($constructClassMethod, $propertyMetadata->getName());

if ($matchedParam instanceof Param) {
// own constructor already has this param → nothing to do
if ($hasOwnConstruct) {
return;
}

// parent constructor has a same-named param; if it is a private promoted
// property, the child cannot access it via $this — add a fresh constructor
// on the child instead of trying to extend the parent signature
if (($matchedParam->flags & Modifiers::PRIVATE) !== 0) {
$childConstructClassMethod = $this->nodeFactory->createPublicMethod(MethodName::CONSTRUCT);
$childConstructClassMethod->params[] = $param;
$this->classInsertManipulator->addAsFirstMethod($class, $childConstructClassMethod);
return;
}

// parent's matching param is protected/public — accessible from child, no add needed
return;
}

// found construct, but only on parent, add to current class
if (! $class->getMethod(MethodName::CONSTRUCT) instanceof ClassMethod) {
if (! $hasOwnConstruct) {
$parentArgs = [];

foreach ($constructClassMethod->params as $originalParam) {
Expand Down Expand Up @@ -334,15 +354,15 @@ private function hasClassPropertyAndDependency(Class_ $class, PropertyMetadata $
return $property instanceof Property;
}

private function hasMethodParameter(ClassMethod $classMethod, string $name): bool
private function matchMethodParameter(ClassMethod $classMethod, string $name): ?Param
{
foreach ($classMethod->params as $param) {
if ($this->nodeNameResolver->isName($param->var, $name)) {
return true;
return $param;
}
}

return false;
return null;
}

private function shouldAddPromotedProperty(Class_ $class, PropertyMetadata $propertyMetadata): bool
Expand Down
Loading