Debian Codegraph @

vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Contracts\Service\Test;
13
14 use PHPUnit\Framework\TestCase;
15 use Psr\Container\ContainerExceptionInterface;
16 use Psr\Container\ContainerInterface;
17 use Psr\Container\NotFoundExceptionInterface;
18 use Symfony\Contracts\Service\ServiceLocatorTrait;
19
20 abstract class ServiceLocatorTestCase extends TestCase
21 {
22 /**
23 * @param array<string, callable> $factories
24 */
25 protected function getServiceLocator(array $factories): ContainerInterface
26 {
27 return new class($factories) implements ContainerInterface {
28 use ServiceLocatorTrait;
29 };
30 }
31
32 public function testHas()
33 {
34 $locator = $this->getServiceLocator([
35 'foo' => static fn () => 'bar',
36 'bar' => static fn () => 'baz',
37 static fn () => 'dummy',
38 ]);
39
40 $this->assertTrue($locator->has('foo'));
41 $this->assertTrue($locator->has('bar'));
42 $this->assertFalse($locator->has('dummy'));
43 }
44
45 public function testGet()
46 {
47 $locator = $this->getServiceLocator([
48 'foo' => static fn () => 'bar',
49 'bar' => static fn () => 'baz',
50 ]);
51
52 $this->assertSame('bar', $locator->get('foo'));
53 $this->assertSame('baz', $locator->get('bar'));
54 }
55
56 public function testGetDoesNotMemoize()
57 {
58 $i = 0;
59 $locator = $this->getServiceLocator([
60 'foo' => static function () use (&$i) {
61 ++$i;
62
63 return 'bar';
64 },
65 ]);
66
67 $this->assertSame('bar', $locator->get('foo'));
68 $this->assertSame('bar', $locator->get('foo'));
69 $this->assertSame(2, $i);
70 }
71
72 public function testThrowsOnUndefinedInternalService()
73 {
74 $locator = $this->getServiceLocator([
75 'foo' => static function () use (&$locator) { return $locator->get('bar'); },
76 ]);
77
78 $this->expectException(NotFoundExceptionInterface::class);
79 $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.');
80
81 $locator->get('foo');
82 }
83
84 public function testThrowsOnCircularReference()
85 {
86 $locator = $this->getServiceLocator([
87 'foo' => static function () use (&$locator) { return $locator->get('bar'); },
88 'bar' => static function () use (&$locator) { return $locator->get('baz'); },
89 'baz' => static function () use (&$locator) { return $locator->get('bar'); },
90 ]);
91
92 $this->expectException(ContainerExceptionInterface::class);
93 $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".');
94
95 $locator->get('foo');
96 }
97 }