|
5 | 5 | namespace Rector\TypeDeclaration\Rector\ClassMethod; |
6 | 6 |
|
7 | 7 | use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\Assign; |
8 | 9 | use PhpParser\Node\Expr\MethodCall; |
| 10 | +use PhpParser\Node\Expr\Variable; |
9 | 11 | use PhpParser\Node\Name; |
10 | 12 | use PhpParser\Node\Stmt\ClassMethod; |
11 | 13 | use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode; |
@@ -141,18 +143,61 @@ private function isGetRepositoryReturnOnly(ClassMethod $classMethod): bool |
141 | 143 | return false; |
142 | 144 | } |
143 | 145 |
|
144 | | - $methodCall = $returns[0]->expr; |
145 | | - if (! $methodCall instanceof MethodCall) { |
146 | | - return false; |
| 146 | + $returnedExpr = $returns[0]->expr; |
| 147 | + |
| 148 | + // direct return: return $this->em->getRepository(...); |
| 149 | + if ($returnedExpr instanceof MethodCall) { |
| 150 | + return $this->isGetRepositoryMethodCall($returnedExpr); |
| 151 | + } |
| 152 | + |
| 153 | + // indirect return: $repo = $this->em->getRepository(...); ...; return $repo; |
| 154 | + if ($returnedExpr instanceof Variable) { |
| 155 | + $assignedMethodCall = $this->findVariableAssignMethodCall($classMethod, $returnedExpr); |
| 156 | + if (! $assignedMethodCall instanceof MethodCall) { |
| 157 | + return false; |
| 158 | + } |
| 159 | + |
| 160 | + return $this->isGetRepositoryMethodCall($assignedMethodCall); |
147 | 161 | } |
148 | 162 |
|
| 163 | + return false; |
| 164 | + } |
| 165 | + |
| 166 | + private function isGetRepositoryMethodCall(MethodCall $methodCall): bool |
| 167 | + { |
149 | 168 | if (! $this->isName($methodCall->name, 'getRepository')) { |
150 | 169 | return false; |
151 | 170 | } |
152 | 171 |
|
153 | 172 | return $this->isEntityManagerType($methodCall); |
154 | 173 | } |
155 | 174 |
|
| 175 | + private function findVariableAssignMethodCall(ClassMethod $classMethod, Variable $variable): ?MethodCall |
| 176 | + { |
| 177 | + /** @var Assign[] $assigns */ |
| 178 | + $assigns = $this->betterNodeFinder->findInstanceOf($classMethod, Assign::class); |
| 179 | + |
| 180 | + $methodCall = null; |
| 181 | + foreach ($assigns as $assign) { |
| 182 | + if (! $assign->var instanceof Variable) { |
| 183 | + continue; |
| 184 | + } |
| 185 | + |
| 186 | + if (! $this->nodeComparator->areNodesEqual($assign->var, $variable)) { |
| 187 | + continue; |
| 188 | + } |
| 189 | + |
| 190 | + // reassigned to something else, cannot be sure of the type |
| 191 | + if (! $assign->expr instanceof MethodCall) { |
| 192 | + return null; |
| 193 | + } |
| 194 | + |
| 195 | + $methodCall = $assign->expr; |
| 196 | + } |
| 197 | + |
| 198 | + return $methodCall; |
| 199 | + } |
| 200 | + |
156 | 201 | private function isEntityManagerType(MethodCall $methodCall): bool |
157 | 202 | { |
158 | 203 | $callerType = $this->nodeTypeResolver->getType($methodCall->var); |
|
0 commit comments