|
2 | 2 |
|
3 | 3 | namespace SaschaEgerer\PhpstanTypo3\Service; |
4 | 4 |
|
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\ClassConstFetch; |
| 7 | +use PhpParser\Node\Expr\StaticCall; |
5 | 8 | use SaschaEgerer\PhpstanTypo3\Contract\ServiceDefinitionChecker; |
6 | 9 |
|
7 | 10 | final class PrototypeServiceDefinitionChecker implements ServiceDefinitionChecker |
8 | 11 | { |
9 | 12 |
|
10 | | - public function isPrototype(ServiceDefinition $serviceDefinition): bool |
| 13 | + public function isPrototype(ServiceDefinition $serviceDefinition, Node $node): bool |
11 | 14 | { |
12 | | - return !$serviceDefinition->isHasTags() && !$serviceDefinition->isHasMethodCalls() && !$serviceDefinition->isHasConstructorArguments(); |
| 15 | + return !$serviceDefinition->isHasTags() && !$serviceDefinition->isHasMethodCalls() && !$serviceDefinition->isHasConstructorArguments() && !$this->canBePrototypeClass($node); |
| 16 | + } |
| 17 | + |
| 18 | + private function extractFirstArgument(StaticCall $node): ?Node |
| 19 | + { |
| 20 | + if (!isset($node->args[0])) { |
| 21 | + return null; |
| 22 | + } |
| 23 | + |
| 24 | + if (!$node->args[0] instanceof Node\Arg) { |
| 25 | + return null; |
| 26 | + } |
| 27 | + |
| 28 | + return $node->args[0]->value; |
| 29 | + } |
| 30 | + |
| 31 | + private function canBePrototypeClass(Node $node): bool |
| 32 | + { |
| 33 | + if (!$node instanceof StaticCall) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + $firstArgument = $this->extractFirstArgument($node); |
| 38 | + |
| 39 | + if (!$firstArgument instanceof ClassConstFetch) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + if (!$firstArgument->class instanceof Node\Name) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + if ($firstArgument->class->isSpecialClassName()) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + /** @var class-string $className */ |
| 52 | + $className = $firstArgument->class->toString(); |
| 53 | + |
| 54 | + $reflection = new \ReflectionClass($className); |
| 55 | + |
| 56 | + $constructorMethod = $reflection->getConstructor(); |
| 57 | + |
| 58 | + if ($constructorMethod === null) { |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + $constructorParameters = $constructorMethod->getParameters(); |
| 63 | + $hasRequiredParameter = false; |
| 64 | + foreach ($constructorParameters as $constructorParameter) { |
| 65 | + if ($constructorParameter->isOptional()) { |
| 66 | + continue; |
| 67 | + } |
| 68 | + $hasRequiredParameter = true; |
| 69 | + } |
| 70 | + |
| 71 | + return $hasRequiredParameter === false; |
13 | 72 | } |
14 | 73 |
|
15 | 74 | } |
0 commit comments