Browse Source

Add PaginatedResultSet::toArray()

This was giving me deprecation warnings that I felt were unnecessary
toil for developers to fix. I couldn't easily find a rector method that
would solve this and I think the ongoing maintenance cost of a one liner
is low.
Mark Story 1 year ago
parent
commit
1732e17242

+ 9 - 0
src/Datasource/Paging/PaginatedInterface.php

@@ -69,6 +69,15 @@ interface PaginatedInterface extends Countable, Traversable
     public function hasNextPage(): bool;
 
     /**
+     * Get the paginated items as an array.
+     *
+     * This will exhaust the iterator `items`.
+     *
+     * @return array
+     */
+    public function toArray(): array;
+
+    /**
      * Get paginated items.
      *
      * @return iterable

+ 12 - 0
src/Datasource/Paging/PaginatedResultSet.php

@@ -64,6 +64,18 @@ class PaginatedResultSet implements IteratorAggregate, JsonSerializable, Paginat
     }
 
     /**
+     * Get the paginated items as an array.
+     *
+     * This will exhaust the iterator `items`.
+     *
+     * @return array<array-key, T>
+     */
+    public function toArray(): array
+    {
+        return iterator_to_array($this->items());
+    }
+
+    /**
      * Get paginated items.
      *
      * @return \Traversable<T> The paginated items result set.

+ 9 - 0
tests/TestCase/Datasource/Paging/PaginatedResultSetTest.php

@@ -17,6 +17,7 @@ declare(strict_types=1);
 namespace Cake\Test\TestCase\Datasource\Paging;
 
 use ArrayIterator;
+use Cake\Collection\Collection;
 use Cake\Datasource\Paging\PaginatedResultSet;
 use Cake\Datasource\ResultSetInterface;
 use Cake\TestSuite\TestCase;
@@ -35,6 +36,14 @@ class PaginatedResultSetTest extends TestCase
         $this->assertInstanceOf(ResultSetInterface::class, $paginatedResults->items());
     }
 
+    public function testToArray(): void
+    {
+        $paginatedResults = new PaginatedResultSet( new Collection([1, 2, 3]), []);
+
+        $out = $paginatedResults->toArray();
+        $this->assertSame([1, 2, 3], $out);
+    }
+
     #[WithoutErrorHandler]
     public function testCall(): void
     {