From 7abe6b277eb876a7485adf82e96b5fbaedab08a9 Mon Sep 17 00:00:00 2001 From: Martin Date: Tue, 10 Dec 2024 17:38:00 +0100 Subject: [PATCH] Make PaginatedResourceCollection usable without Resource object --- src/Resource/PaginatedResourceCollection.php | 26 +++++++++++--------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/Resource/PaginatedResourceCollection.php b/src/Resource/PaginatedResourceCollection.php index 89b2591..e5c0559 100644 --- a/src/Resource/PaginatedResourceCollection.php +++ b/src/Resource/PaginatedResourceCollection.php @@ -6,17 +6,22 @@ class PaginatedResourceCollection extends AbstractResource implements \IteratorAggregate, \Countable { /** - * @var string + * @var ?string */ private $resourceClass; /** + * Provide your resource class name if you want that collection return + * those specific resource class rather than an HalResource + * * @param Hal\HalResource $resource - * @param string $resourceClass + * @param ?string $resourceClass */ - public function __construct(Hal\HalResource $resource, $resourceClass) + public function __construct(Hal\HalResource $resource, $resourceClass = null) { - $this->resourceClass = (string) $resourceClass; + if (null !== $resourceClass) { + $this->resourceClass = (string) $resourceClass; + } parent::__construct($resource, false); } @@ -90,21 +95,20 @@ public function next() return new static($resource, $this->resourceClass); } - /** - * @inheritdoc - */ #[\ReturnTypeWillChange] public function getIterator() { $data = current($this->resource->getAllResources()) ?: []; + foreach ($data as $item) { - yield new $this->resourceClass($item); + if (null !== $this->resourceClass) { + $item = new $this->resourceClass($item); + } + + yield $item; } } - /** - * @inheritdoc - */ #[\ReturnTypeWillChange] public function count() {