Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: LazyServiceFactory does not reset initializer in proxy class when building dependency fails #250

Open
wants to merge 2 commits into
base: 4.4.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Proxy/LazyServiceFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public function __invoke(
): VirtualProxyInterface {
if (isset($this->servicesMap[$name])) {
$initializer = static function (&$wrappedInstance, LazyLoadingInterface $proxy) use ($callback): bool {
$proxy->setProxyInitializer(null);
$wrappedInstance = $callback();
$proxy->setProxyInitializer(null);

return true;
};
Expand Down
33 changes: 33 additions & 0 deletions test/Proxy/LazyServiceFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use ProxyManager\Proxy\LazyLoadingInterface;
use ProxyManager\Proxy\VirtualProxyInterface;
use Psr\Container\ContainerInterface;
use RuntimeException;

#[CoversClass(LazyServiceFactory::class)]
final class LazyServiceFactoryTest extends TestCase
Expand Down Expand Up @@ -94,4 +95,36 @@ static function ($className, $initializer) use ($expectedService, $proxy): MockO

self::assertSame($expectedService, $result, 'service created not match the expected');
}

public function testDoesNotResetInitializerWhenCallbackThrowsException(): void
{
$exception = new RuntimeException('Test exception');
$callback = function () use ($exception): void {
throw $exception;
};

$proxy = $this->createMock(LazyLoadingInterface::class);
$proxy
->expects(self::never())
->method('setProxyInitializer');

$expectedService = $this->createMock(VirtualProxyInterface::class);

$this->proxyFactory
->expects(self::once())
->method('createProxy')
->willReturnCallback(
/** @psalm-suppress UnusedVariable */
static function (string $className, callable $initializer) use ($expectedService, $proxy): MockObject {
$wrappedInstance = null;
$initializer($wrappedInstance, $proxy);
return $expectedService;
}
);

$this->expectExceptionObject($exception);
$result = $this->factory->__invoke($this->container, 'fooService', $callback);

self::assertSame($expectedService, $result);
}
}
Loading