Skip to content

Commit

Permalink
Honor existing return types when generating decorators
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Apr 30, 2022
1 parent 581ab35 commit 3d3c71f
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
10 changes: 9 additions & 1 deletion src/ProxyManager/Generator/MagicMethodGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Laminas\Code\Generator\ParameterGenerator;
use ReflectionClass;
use ReflectionNamedType;

use function strtolower;

Expand All @@ -31,6 +32,13 @@ public function __construct(ReflectionClass $originalClass, string $name, array
return;
}

$this->setReturnsReference($originalClass->getMethod($name)->returnsReference());
$originalMethod = $originalClass->getMethod($name);
$returnType = $originalMethod->getReturnType();

if ($returnType instanceof ReflectionNamedType) {
$this->setReturnType($returnType->getName());
}

$this->setReturnsReference($originalMethod->returnsReference());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
use Laminas\Code\Reflection\MethodReflection;
use ProxyManager\Generator\MethodGenerator;
use ProxyManager\Generator\Util\IdentifierSuffixer;
use ReflectionNamedType;

use function in_array;

/**
* Method decorator for null objects
Expand All @@ -20,10 +23,13 @@ public static function generateMethod(MethodReflection $originalMethod): self
{
$method = static::fromReflectionWithoutBodyAndDocBlock($originalMethod);

if ($originalMethod->returnsReference()) {
$returnType = $originalMethod->getReturnType();
$nullCast = $returnType instanceof ReflectionNamedType && in_array($returnType->getName(), ['array', 'float', 'int', 'string'], true) ? '(' . $returnType->getName() . ') ' : '';

if ($originalMethod->returnsReference() || $nullCast !== '') {
$reference = IdentifierSuffixer::getIdentifier('ref');

$method->setBody("\$reference = null;\nreturn \$" . $reference . ';');
$method->setBody('$' . $reference . ' = ' . $nullCast . "null;\nreturn \$" . $reference . ';');
}

return $method;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function testGeneratesValidCode(string $className): void
$callback = [$proxy, $method->getName()];

self::assertIsCallable($callback);
self::assertNull($callback());
self::assertEmpty($callback());
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/ProxyManagerTestAsset/ClassWithMagicMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function __unset($name)
return (bool) $name;
}

public function __sleep()
public function __sleep(): array
{
return [];
}
Expand Down

0 comments on commit 3d3c71f

Please sign in to comment.