From 281885a2d58c7ffc0b3e1ac2933fc6df71d90cad Mon Sep 17 00:00:00 2001 From: Julien Rosset Date: Wed, 11 Oct 2023 19:04:11 +0200 Subject: [PATCH] Fix slice and sliceSelf when collection is empty --- src/Collections/Collection.php | 10 +++++++--- src/Collections/ImmutableCollection.php | 7 +++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Collections/Collection.php b/src/Collections/Collection.php index 208b964..211a2eb 100644 --- a/src/Collections/Collection.php +++ b/src/Collections/Collection.php @@ -126,9 +126,13 @@ class Collection extends ImmutableCollection implements ICollection { * @inheritDoc */ public function sliceSelf (int $offset, ?int $length = null): static { - $this->_checkOffset($offset); - - $this->elements = array_slice($this->elements, $offset, $length, true); + if ($this->count() === 0) { + $this->elements = []; + } + else { + $this->_checkOffset($offset); + $this->elements = array_slice($this->elements, $offset, $length, true); + } return $this; } diff --git a/src/Collections/ImmutableCollection.php b/src/Collections/ImmutableCollection.php index fb62bb7..9a5188a 100644 --- a/src/Collections/ImmutableCollection.php +++ b/src/Collections/ImmutableCollection.php @@ -289,9 +289,12 @@ class ImmutableCollection implements IImmutableCollection { * @inheritDoc */ public function slice (int $offset, ?int $length = null): static { - $this->_checkOffset($offset); - $output = new static(); + if ($this->count() === 0) { + return $output; + } + + $this->_checkOffset($offset); $currentIndex = 0; foreach ($this->elements as $key => $value) {