Browse Source

[DependencyInjection] fixed false positive when detecting circular references if a service throws an exception during creation

Kris Wallsmith 14 years ago
parent
commit
8c45a21637

+ 6 - 1
src/Symfony/Component/DependencyInjection/Container.php

@@ -223,7 +223,12 @@ class Container implements ContainerInterface
         if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
             $this->loading[$id] = true;
 
-            $service = $this->$method();
+            try {
+                $service = $this->$method();
+            } catch (\Exception $e) {
+                unset($this->loading[$id]);
+                throw $e;
+            }
 
             unset($this->loading[$id]);
 

+ 25 - 1
tests/Symfony/Tests/Component/DependencyInjection/ContainerTest.php

@@ -98,7 +98,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals(array('service_container', 'foo', 'bar'), $sc->getServiceIds(), '->getServiceIds() returns all defined service ids');
 
         $sc = new ProjectServiceContainer();
-        $this->assertEquals(array('scoped', 'scoped_foo', 'bar', 'foo_bar', 'foo.baz', 'circular', 'service_container'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods');
+        $this->assertEquals(array('scoped', 'scoped_foo', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'service_container'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods');
     }
 
     /**
@@ -337,6 +337,25 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
         $this->assertFalse($c->isScopeActive('foo'));
     }
 
+    public function testGetThrowsException()
+    {
+        $c = new ProjectServiceContainer();
+
+        try {
+            $c->get('throw_exception');
+            $this->fail();
+        } catch (\Exception $e) {
+            $this->assertEquals('Something went terribly wrong!', $e->getMessage());
+        }
+
+        try {
+            $c->get('throw_exception');
+            $this->fail();
+        } catch (\Exception $e) {
+            $this->assertEquals('Something went terribly wrong!', $e->getMessage());
+        }
+    }
+
     public function getInvalidParentScopes()
     {
         return array(
@@ -412,4 +431,9 @@ class ProjectServiceContainer extends Container
     {
         return $this->get('circular');
     }
+
+    protected function getThrowExceptionService()
+    {
+        throw new \Exception('Something went terribly wrong!');
+    }
 }