Skip to content

Commit 8a2f8fa

Browse files
committed
Fix inserting constructor after traits
1 parent 87c35b2 commit 8a2f8fa

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

src/Rector/Class_/AddMethodCallToConstructorForClassesUsingTraitRector.php

+26-4
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use PhpParser\Node\Stmt\Class_;
1212
use PhpParser\Node\Stmt\ClassMethod;
1313
use PhpParser\Node\Stmt\Expression;
14+
use PhpParser\Node\Stmt\TraitUse;
1415
use Rector\Contract\Rector\ConfigurableRectorInterface;
1516
use Rector\Exception\ShouldNotHappenException;
1617
use Rector\NodeManipulator\ClassInsertManipulator;
@@ -154,15 +155,36 @@ private function getOrCreateConstructorMethod(Class_ $node): ClassMethod
154155
{
155156
$constructor = $node->getMethod(MethodName::CONSTRUCT);
156157

157-
if (null === $constructor) {
158-
$constructor = $this->constructorClassMethodFactory->createConstructorClassMethod([], []);
159-
$constructor->stmts = [new Expression($this->syliusNodeFactory->createParentConstructWithParams([]))];
160-
$this->classInsertManipulator->addAsFirstMethod($node, $constructor);
158+
if ($constructor !== null) {
159+
return $constructor;
161160
}
162161

162+
$constructor = $this->constructorClassMethodFactory->createConstructorClassMethod([], []);
163+
$constructor->stmts = [
164+
new Expression($this->syliusNodeFactory->createParentConstructWithParams([]))
165+
];
166+
167+
$this->insertConstructorAfterTraits($node, $constructor);
168+
163169
return $constructor;
164170
}
165171

172+
private function insertConstructorAfterTraits(Class_ $node, ClassMethod $constructor): void
173+
{
174+
$traitUses = [];
175+
$others = [];
176+
177+
foreach ($node->stmts as $stmt) {
178+
if ($stmt instanceof TraitUse) {
179+
$traitUses[] = $stmt;
180+
} else {
181+
$others[] = $stmt;
182+
}
183+
}
184+
185+
$node->stmts = array_merge($traitUses, [$constructor], $others);
186+
}
187+
166188
private function isConstructMethodCallAlreadyExisting(ClassMethod $constructor, MethodCall $newMethodCall): bool
167189
{
168190
foreach ($constructor->stmts as $stmt) {

0 commit comments

Comments
 (0)