Browse Source

Issuing a count() on a Collection should throw an exception

Yves P 10 years ago
parent
commit
c96f30ce7f
2 changed files with 28 additions and 0 deletions
  1. 15 0
      src/Collection/Collection.php
  2. 13 0
      tests/TestCase/Collection/CollectionTest.php

+ 15 - 0
src/Collection/Collection.php

@@ -17,6 +17,7 @@ namespace Cake\Collection;
 use ArrayIterator;
 use InvalidArgumentException;
 use IteratorIterator;
+use LogicException;
 use Serializable;
 use Traversable;
 
@@ -72,6 +73,20 @@ class Collection extends IteratorIterator implements CollectionInterface, Serial
     }
 
     /**
+     * Throws an exception.
+     *
+     * Issuing a count on a Collection can have many side effects, some making the
+     * Collection unusable after the count operation.
+     *
+     * @return void
+     * @throws \LogicException
+     */
+    public function count()
+    {
+        throw new LogicException('You cannot issue a count on a Collection.');
+    }
+
+    /**
      * Returns an array that can be used to describe the internal state of this
      * object.
      *

+ 13 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -612,6 +612,19 @@ class CollectionTest extends TestCase
     }
 
     /**
+     * Tests that issuing a count will throw an exception
+     *
+     * @expectedException \LogicException
+     * @return void
+     */
+    public function testCollectionCount()
+    {
+        $data = [1, 2, 3, 4];
+        $collection = new Collection($data);
+        $collection->count();
+    }
+
+    /**
      * Tests take method
      *
      * @return void