Browse Source

[Translation] added detection for circular references when adding a fallback catalogue

Fabien Potencier 13 years ago
parent
commit
45b218e7c4

+ 20 - 0
src/Symfony/Component/Translation/MessageCatalogue.php

@@ -26,6 +26,7 @@ class MessageCatalogue implements MessageCatalogueInterface
     private $locale;
     private $resources;
     private $fallbackCatalogue;
+    private $parent;
 
     /**
      * Constructor.
@@ -183,6 +184,15 @@ class MessageCatalogue implements MessageCatalogueInterface
      */
     public function addFallbackCatalogue(MessageCatalogueInterface $catalogue)
     {
+        // detect circular references
+        $c = $this;
+        do {
+            if ($c->getLocale() === $catalogue->getLocale()) {
+                throw new \LogicException(sprintf('Circular reference detected when adding a fallback catalogue for locale "%s".', $catalogue->getLocale()));
+            }
+        } while ($c = $c->getParent());
+
+        $catalogue->setParent($this);
         $this->fallbackCatalogue = $catalogue;
 
         foreach ($catalogue->getResources() as $resource) {
@@ -190,6 +200,16 @@ class MessageCatalogue implements MessageCatalogueInterface
         }
     }
 
+    public function getParent()
+    {
+        return $this->parent;
+    }
+
+    public function setParent(self $parent)
+    {
+        $this->parent = $parent;
+    }
+
     /**
      * {@inheritdoc}
      *

+ 12 - 0
tests/Symfony/Tests/Component/Translation/MessageCatalogTest.php

@@ -124,6 +124,18 @@ class MessageCatalogueTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals(array($r, $r1), $catalogue->getResources());
     }
 
+    /**
+     * @expectedException LogicException
+     */
+    public function testAddFallbackCatalogueWithCircularReference()
+    {
+        $main = new MessageCatalogue('en_US');
+        $fallback = new MessageCatalogue('fr_FR');
+
+        $fallback->addFallbackCatalogue($main);
+        $main->addFallbackCatalogue($fallback);
+    }
+
     /**
      * @expectedException LogicException
      */