Skip to content

Commit

Permalink
fix: callback in LazyServiceFactory does not reset initializer in pro…
Browse files Browse the repository at this point in the history
…xy class when building dependency fails

Signed-off-by: vdmorozov <[email protected]>
  • Loading branch information
vdmorozov committed Dec 11, 2024
1 parent 340409a commit b0937fd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
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
32 changes: 32 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,35 @@ 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(
static function (string $className, callable $initializer) use ($expectedService, $proxy): MockObject {
$wrappedInstance = null;

Check failure on line 118 in test/Proxy/LazyServiceFactoryTest.php

View workflow job for this annotation

GitHub Actions / ci / QA Checks (Psalm [8.1, locked], ubuntu-latest, laminas/laminas-continuous-integration-action@v1, ...

UnusedVariable

test/Proxy/LazyServiceFactoryTest.php:118:21: UnusedVariable: $wrappedInstance is never referenced or the value is not used (see https://psalm.dev/077)
$initializer($wrappedInstance, $proxy);
return $expectedService;
}
);

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

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

0 comments on commit b0937fd

Please sign in to comment.