Browse Source

Pass the locator to the constructor.

Robert Pustułka 8 years ago
parent
commit
cb4d38da95

+ 16 - 0
src/ORM/AssociationCollection.php

@@ -17,6 +17,7 @@ namespace Cake\ORM;
 use ArrayIterator;
 use Cake\Datasource\EntityInterface;
 use Cake\ORM\Locator\LocatorAwareTrait;
+use Cake\ORM\Locator\LocatorInterface;
 use InvalidArgumentException;
 use IteratorAggregate;
 
@@ -40,6 +41,21 @@ class AssociationCollection implements IteratorAggregate
     protected $_items = [];
 
     /**
+     * Constructor.
+     *
+     * Sets the default table locator for associations.
+     * If no locator is provided, the global one will be used.
+     *
+     * @param \Cake\ORM\Locator\LocatorInterface|null $tableLocator Table locator instance.
+     */
+    public function __construct(LocatorInterface $tableLocator = null)
+    {
+        if ($tableLocator !== null) {
+            $this->_tableLocator = $tableLocator;
+        }
+    }
+
+    /**
      * Add an association to the collection
      *
      * If the alias added contains a `.` the part preceding the `.` will be dropped.

+ 1 - 2
src/ORM/Locator/TableLocator.php

@@ -213,8 +213,7 @@ class TableLocator implements LocatorInterface
             $options['connection'] = ConnectionManager::get($connectionName);
         }
         if (empty($options['associations'])) {
-            $associations = new AssociationCollection();
-            $associations->setTableLocator($this);
+            $associations = new AssociationCollection($this);
             $options['associations'] = $associations;
         }
 

+ 15 - 0
tests/TestCase/ORM/AssociationCollectionTest.php

@@ -19,6 +19,7 @@ use Cake\ORM\Association\BelongsTo;
 use Cake\ORM\Association\BelongsToMany;
 use Cake\ORM\Entity;
 use Cake\ORM\Locator\LocatorInterface;
+use Cake\ORM\TableRegistry;
 use Cake\TestSuite\TestCase;
 
 /**
@@ -43,6 +44,20 @@ class AssociationCollectionTest extends TestCase
     }
 
     /**
+     * Test the constructor.
+     *
+     * @return void
+     */
+    public function testConstructor()
+    {
+        $this->assertSame(TableRegistry::getTableLocator(), $this->associations->getTableLocator());
+
+        $tableLocator = $this->createMock(LocatorInterface::class);
+        $associations = new AssociationCollection($tableLocator);
+        $this->assertSame($tableLocator, $associations->getTableLocator());
+    }
+
+    /**
      * Test the simple add/has and get methods.
      *
      * @return void