mirror of
https://github.com/wiosna-dev/common-library.git
synced 2026-03-12 17:41:50 +01:00
Create clear() & limit() methods in BaseCollection class
This commit is contained in:
@@ -223,6 +223,41 @@ abstract class BaseCollection implements CollectionInterface
|
||||
return null !== $index && false !== $index;
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->elements = [];
|
||||
}
|
||||
|
||||
public function limit(int $max, int $offset = 0): CollectionInterface
|
||||
{
|
||||
$result = clone $this;
|
||||
|
||||
$negativeMax = $max <= 0;
|
||||
$exceededMax = $max >= $this->count();
|
||||
|
||||
if ($negativeMax || $exceededMax) {
|
||||
if ($negativeMax) {
|
||||
$result->clear();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
$iteration = -1;
|
||||
|
||||
foreach ($result as $index => $element) {
|
||||
$iteration++;
|
||||
|
||||
if ($iteration < $offset || ($iteration >= $offset && $iteration < $max)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
unset($result[$index]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->elements);
|
||||
|
||||
Reference in New Issue
Block a user