ServiceLocatorTestCase.php
75 lines
| 1 | <?php |
| 2 | namespace MailPoetVendor\Symfony\Contracts\Service\Test; |
| 3 | if (!defined('ABSPATH')) exit; |
| 4 | use MailPoetVendor\PHPUnit\Framework\TestCase; |
| 5 | use MailPoetVendor\Psr\Container\ContainerInterface; |
| 6 | use MailPoetVendor\Symfony\Contracts\Service\ServiceLocatorTrait; |
| 7 | abstract class ServiceLocatorTestCase extends TestCase |
| 8 | { |
| 9 | protected function getServiceLocator(array $factories) |
| 10 | { |
| 11 | return new class($factories) implements ContainerInterface |
| 12 | { |
| 13 | use ServiceLocatorTrait; |
| 14 | }; |
| 15 | } |
| 16 | public function testHas() |
| 17 | { |
| 18 | $locator = $this->getServiceLocator(['foo' => function () { |
| 19 | return 'bar'; |
| 20 | }, 'bar' => function () { |
| 21 | return 'baz'; |
| 22 | }, function () { |
| 23 | return 'dummy'; |
| 24 | }]); |
| 25 | $this->assertTrue($locator->has('foo')); |
| 26 | $this->assertTrue($locator->has('bar')); |
| 27 | $this->assertFalse($locator->has('dummy')); |
| 28 | } |
| 29 | public function testGet() |
| 30 | { |
| 31 | $locator = $this->getServiceLocator(['foo' => function () { |
| 32 | return 'bar'; |
| 33 | }, 'bar' => function () { |
| 34 | return 'baz'; |
| 35 | }]); |
| 36 | $this->assertSame('bar', $locator->get('foo')); |
| 37 | $this->assertSame('baz', $locator->get('bar')); |
| 38 | } |
| 39 | public function testGetDoesNotMemoize() |
| 40 | { |
| 41 | $i = 0; |
| 42 | $locator = $this->getServiceLocator(['foo' => function () use(&$i) { |
| 43 | ++$i; |
| 44 | return 'bar'; |
| 45 | }]); |
| 46 | $this->assertSame('bar', $locator->get('foo')); |
| 47 | $this->assertSame('bar', $locator->get('foo')); |
| 48 | $this->assertSame(2, $i); |
| 49 | } |
| 50 | public function testThrowsOnUndefinedInternalService() |
| 51 | { |
| 52 | if (!$this->getExpectedException()) { |
| 53 | $this->expectException(\MailPoetVendor\Psr\Container\NotFoundExceptionInterface::class); |
| 54 | $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); |
| 55 | } |
| 56 | $locator = $this->getServiceLocator(['foo' => function () use(&$locator) { |
| 57 | return $locator->get('bar'); |
| 58 | }]); |
| 59 | $locator->get('foo'); |
| 60 | } |
| 61 | public function testThrowsOnCircularReference() |
| 62 | { |
| 63 | $this->expectException(\MailPoetVendor\Psr\Container\ContainerExceptionInterface::class); |
| 64 | $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); |
| 65 | $locator = $this->getServiceLocator(['foo' => function () use(&$locator) { |
| 66 | return $locator->get('bar'); |
| 67 | }, 'bar' => function () use(&$locator) { |
| 68 | return $locator->get('baz'); |
| 69 | }, 'baz' => function () use(&$locator) { |
| 70 | return $locator->get('bar'); |
| 71 | }]); |
| 72 | $locator->get('foo'); |
| 73 | } |
| 74 | } |
| 75 |