From 4993b1c14c8a299b8e2f92e5ac6bac20f1586216 Mon Sep 17 00:00:00 2001 From: "Konstantin.Myakshin" Date: Thu, 17 Aug 2017 13:33:52 +0300 Subject: [PATCH] Allow to get alternatives when ServiceNotFoundException occurs. --- .../Exception/ServiceNotFoundException.php | 7 +++++++ .../DependencyInjection/Tests/ServiceLocatorTest.php | 11 +++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Exception/ServiceNotFoundException.php b/src/Symfony/Component/DependencyInjection/Exception/ServiceNotFoundException.php index 0194c4f372279..5de10d3bcbfc0 100644 --- a/src/Symfony/Component/DependencyInjection/Exception/ServiceNotFoundException.php +++ b/src/Symfony/Component/DependencyInjection/Exception/ServiceNotFoundException.php @@ -22,6 +22,7 @@ class ServiceNotFoundException extends InvalidArgumentException implements NotFo { private $id; private $sourceId; + private $alternatives; public function __construct($id, $sourceId = null, \Exception $previous = null, array $alternatives = array()) { @@ -44,6 +45,7 @@ public function __construct($id, $sourceId = null, \Exception $previous = null, $this->id = $id; $this->sourceId = $sourceId; + $this->alternatives = $alternatives; } public function getId() @@ -55,4 +57,9 @@ public function getSourceId() { return $this->sourceId; } + + public function getAlternatives() + { + return $this->alternatives; + } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index 6900fd7ea4490..a1e2fff50fdbe 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ServiceLocator; class ServiceLocatorTest extends TestCase @@ -58,7 +59,7 @@ public function testGetDoesNotMemoize() /** * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage You have requested a non-existent service "dummy" + * @expectedExceptionMessage You have requested a non-existent service "dummy". Did you mean one of these: "foo", "bar"? */ public function testGetThrowsOnUndefinedService() { @@ -67,7 +68,13 @@ public function testGetThrowsOnUndefinedService() 'bar' => function () { return 'baz'; }, )); - $locator->get('dummy'); + try { + $locator->get('dummy'); + } catch (ServiceNotFoundException $e) { + $this->assertSame(array('foo', 'bar'), $e->getAlternatives()); + + throw $e; + } } public function testInvoke()