Browse Source

Merge pull request #6441 from davidyell/3.0-iteratable-associations

Allow AssociationCollection to be iterated
Mark Story 11 years ago
parent
commit
eff0242bc0
2 changed files with 30 additions and 1 deletions
  1. 13 1
      src/ORM/AssociationCollection.php
  2. 17 0
      tests/TestCase/ORM/AssociationCollectionTest.php

+ 13 - 1
src/ORM/AssociationCollection.php

@@ -14,11 +14,13 @@
  */
 namespace Cake\ORM;
 
+use ArrayIterator;
 use Cake\ORM\Association;
 use Cake\ORM\AssociationsNormalizerTrait;
 use Cake\ORM\Entity;
 use Cake\ORM\Table;
 use InvalidArgumentException;
+use IteratorAggregate;
 
 /**
  * A container/collection for association classes.
@@ -26,7 +28,7 @@ use InvalidArgumentException;
  * Contains methods for managing associations, and
  * ordering operations around saving and deleting.
  */
-class AssociationCollection
+class AssociationCollection implements IteratorAggregate
 {
 
     use AssociationsNormalizerTrait;
@@ -292,4 +294,14 @@ class AssociationCollection
 
         return $this->_normalizeAssociations($keys);
     }
+
+    /**
+     * Allow looping through the associations
+     *
+     * @return ArrayIterator
+     */
+    public function getIterator()
+    {
+        return new ArrayIterator($this->_items);
+    }
 }

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

@@ -367,4 +367,21 @@ class AssociationCollectionTest extends TestCase
         $expected = ['users' => [], 'categories' => []];
         $this->assertSame($expected, $this->associations->normalizeKeys(true));
     }
+
+    /**
+     * Ensure that the association collection can be iterated.
+     *
+     * @return void
+     */
+    public function testAssociationsCanBeIterated()
+    {
+        $belongsTo = new BelongsTo('');
+        $this->associations->add('Users', $belongsTo);
+        $belongsToMany = new BelongsToMany('');
+        $this->associations->add('Cart', $belongsToMany);
+
+        $expected = ['users' => $belongsTo, 'cart' => $belongsToMany];
+        $result = iterator_to_array($this->associations, true);
+        $this->assertSame($expected, $result);
+    }
 }