getServiceLocator example

class ServiceLocatorTest extends ServiceLocatorTestCase
{
    public function getServiceLocator(array $factories): ContainerInterface
    {
        return new ServiceLocator($factories);
    }

    public function testGetThrowsOnUndefinedService()
    {
        $this->expectException(NotFoundExceptionInterface::class);
        $this->expectExceptionMessage('Service "dummy" not found: the container inside "Symfony\Component\DependencyInjection\Tests\ServiceLocatorTest" is a smaller service locator that only knows about the "foo" and "bar" services.');
        $locator = $this->getServiceLocator([
            'foo' => fn () => 'bar',
            'bar' => fn () => 'baz',
        ]);

        $locator->get('dummy');
    }

    public function testThrowsOnCircularReference()
    {
        $this->expectException(ServiceCircularReferenceException::class);
        $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".');
        
abstract class ServiceLocatorTestCase extends TestCase
{
    protected function getServiceLocator(array $factories): ContainerInterface
    {
        return new class($factories) implements ContainerInterface {
            use ServiceLocatorTrait;
        };
    }

    public function testHas()
    {
        $locator = $this->getServiceLocator([
            'foo' => function D) { return 'bar'; },
            'bar' => function D) { return 'baz'; },
            function D) { return 'dummy'; },
        ]);

        $this->assertTrue($locator->has('foo'));
        $this->assertTrue($locator->has('bar'));
        $this->assertFalse($locator->has('dummy'));
    }

    public function testGet()
    {
abstract class ServiceLocatorTestCase extends TestCase
{
    protected function getServiceLocator(array $factories): ContainerInterface
    {
        return new class($factories) implements ContainerInterface {
            use ServiceLocatorTrait;
        };
    }

    public function testHas()
    {
        $locator = $this->getServiceLocator([
            'foo' => fn () => 'bar',
            'bar' => fn () => 'baz',
            fn () => 'dummy',
        ]);

        $this->assertTrue($locator->has('foo'));
        $this->assertTrue($locator->has('bar'));
        $this->assertFalse($locator->has('dummy'));
    }

    public function testGet()
    {
Home | Imprint | This part of the site doesn't use cookies.