Skip to content

Commit 943886f

Browse files
committed
return the return type of the called method when generating factory methods and calls
1 parent d7bde6c commit 943886f

File tree

6 files changed

+185
-162
lines changed

6 files changed

+185
-162
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
"phpunit/php-file-iterator": "^1.4 || ^2.0 || ^3.0",
2323
"phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0",
2424
"phpstan/phpstan": "^2.1",
25-
"phpstan/phpstan-phpunit": "^2.0"
25+
"phpstan/phpstan-phpunit": "^2.0",
26+
"symfony/var-dumper": "^5.4"
2627
},
2728

2829
"replace": {

generator/FactoryFile.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,19 @@ public function generateDeclarationArguments(FactoryMethod $method)
8585

8686
public function generateReturnType(FactoryMethod $method): string
8787
{
88-
return '\Hamcrest\Matcher';
88+
$call = $method->getCalls()[0];
89+
if (!$call instanceof FactoryCall) {
90+
throw new Exception('The first call in the FactoryMethod cannot be used to determine the return type. Method: '.$method->getName());
91+
}
92+
93+
$returnType = $call->getMethod()->getReturnType();
94+
95+
if (!$returnType) {
96+
dump($method);
97+
throw new \Exception('The first calls FactoryMethod cannot be used to determine the return type. Method: '.$method->getName());
98+
}
99+
100+
return sprintf('\\%s', $returnType);
89101
}
90102

91103
public function generateImport(FactoryMethod $method)

generator/FactoryMethod.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,21 @@ public function getFullName()
214214
return $this->getClassName() . '::' . $this->getName();
215215
}
216216

217+
public function getReturnType(): ?string
218+
{
219+
if (!$this->reflector->hasReturnType()) {
220+
return null;
221+
}
222+
223+
$returnType = $this->reflector->getReturnType()->getName();
224+
225+
if ($returnType === 'self') {
226+
return $this->reflector->getDeclaringClass()->getName();
227+
}
228+
229+
return $returnType;
230+
}
231+
217232
public function getCommentText()
218233
{
219234
return implode("\n", $this->comment);

0 commit comments

Comments
 (0)