Skip to content

Commit 2564fba

Browse files
committed
return the return type of the called method when generating factory methods and calls
1 parent 39afaff commit 2564fba

File tree

4 files changed

+31
-4
lines changed

4 files changed

+31
-4
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
"phpunit/php-file-iterator": "^1.4 || ^2.0 || ^3.0",
2525
"phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0",
2626
"phpstan/phpstan": "^2.1",
27-
"phpstan/phpstan-phpunit": "^2.0"
27+
"phpstan/phpstan-phpunit": "^2.0",
28+
"symfony/var-dumper": "^5.4"
2829
},
2930

3031
"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);

hamcrest/Hamcrest/Core/IsAnything.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ public function describeTo(Description $description): void
3535
*
3636
* @param string $description A meaningful string used when describing itself.
3737
*
38-
* @return \Hamcrest\Core\IsAnything
3938
* @factory
4039
*/
41-
public static function anything(string $description = 'ANYTHING')
40+
public static function anything(string $description = 'ANYTHING'): self
4241
{
4342
return new self($description);
4443
}

0 commit comments

Comments
 (0)