Browse Source

Add __debugInfo() to Collection.

Mark Scherer 11 years ago
parent
commit
eaa9179c36
2 changed files with 55 additions and 0 deletions
  1. 13 0
      src/Collection/Collection.php
  2. 42 0
      tests/TestCase/Collection/CollectionTest.php

+ 13 - 0
src/Collection/Collection.php

@@ -48,4 +48,17 @@ class Collection extends IteratorIterator implements CollectionInterface
 
         parent::__construct($items);
     }
+
+    /**
+     * Returns an array that can be used to describe the internal state of this
+     * object.
+     *
+     * @return array
+     */
+    public function __debugInfo()
+    {
+        return [
+            'count' => iterator_count($this),
+        ];
+    }
 }

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

@@ -1163,4 +1163,46 @@ class CollectionTest extends TestCase
 
         $this->assertEquals([1, 2, 3, 1, 2, 3], $collection->toList());
     }
+
+    /**
+     * Tests __debugInfo() or debug() usage
+     *
+     * @return void
+     */
+    public function testDebug()
+    {
+        $items = [1, 2, 3];
+
+        $collection = new Collection($items);
+
+        $result = $collection->__debugInfo();
+        $expected = [
+            'count' => 3,
+        ];
+        $this->assertSame($expected, $result);
+
+        // Calling it again will rewind
+        $result = $collection->__debugInfo();
+        $expected = [
+            'count' => 3,
+        ];
+        $this->assertSame($expected, $result);
+
+        // Make sure it also works with non rewindable iterators
+        $iterator = new NoRewindIterator(new ArrayIterator($items));
+        $collection = new Collection($iterator);
+
+        $result = $collection->__debugInfo();
+        $expected = [
+            'count' => 3,
+        ];
+        $this->assertSame($expected, $result);
+
+        // Calling it again will in this case not rewind
+        $result = $collection->__debugInfo();
+        $expected = [
+            'count' => 0,
+        ];
+        $this->assertSame($expected, $result);
+    }
 }