| 1 |
<?php |
| 2 |
|
| 3 |
namespace App\Billingo\Service; |
| 4 |
|
| 5 |
use App\Billingo\Models\BillingoModel; |
| 6 |
use Closure; |
| 7 |
|
| 8 |
class BillingoCollection |
| 9 |
{ |
| 10 |
private array $collection; |
| 11 |
private string $collectionType; |
| 12 |
|
| 13 |
public function __construct(array $collection) |
| 14 |
{ |
| 15 |
$this->collection = $collection; |
| 16 |
|
| 17 |
if (!empty($collection)) { |
| 18 |
$this->collectionType = get_class($collection[0]); |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
public function get(int $index = null): mixed |
| 23 |
{ |
| 24 |
return ($index === null || !isset($this->collection[$index - 1])) |
| 25 |
? $this->collection |
| 26 |
: $this->collection[$index - 1]; |
| 27 |
} |
| 28 |
|
| 29 |
public function first(): mixed |
| 30 |
{ |
| 31 |
return $this->get(1); |
| 32 |
} |
| 33 |
|
| 34 |
public function map(Closure $closure): self |
| 35 |
{ |
| 36 |
$modified = []; |
| 37 |
|
| 38 |
foreach ($this->collection as $item) { |
| 39 |
$modified[] = $closure($item); |
| 40 |
} |
| 41 |
|
| 42 |
$this->collection = $modified; |
| 43 |
|
| 44 |
return $this; |
| 45 |
} |
| 46 |
|
| 47 |
public function each(Closure $closure): self |
| 48 |
{ |
| 49 |
foreach ($this->collection as $item) { |
| 50 |
$closure($item); |
| 51 |
} |
| 52 |
|
| 53 |
return $this; |
| 54 |
} |
| 55 |
|
| 56 |
public function pluck(string $property): array |
| 57 |
{ |
| 58 |
$modified = []; |
| 59 |
|
| 60 |
foreach ($this->collection as $item) { |
| 61 |
$modified[] = $item->$property; |
| 62 |
} |
| 63 |
|
| 64 |
return $modified; |
| 65 |
} |
| 66 |
|
| 67 |
public function append(BillingoModel $billingoModel): bool|self |
| 68 |
{ |
| 69 |
if (get_class($billingoModel) !== $this->collectionType) { |
| 70 |
|
| 71 |
return false; |
| 72 |
} |
| 73 |
|
| 74 |
$this->collection[] = $billingoModel; |
| 75 |
|
| 76 |
return $this; |
| 77 |
} |
| 78 |
|
| 79 |
public function remove(int $index): self |
| 80 |
{ |
| 81 |
if (isset($this->collection[$index - 1])) { |
| 82 |
unset($this->collection[$index - 1]); |
| 83 |
} |
| 84 |
|
| 85 |
return $this; |
| 86 |
} |
| 87 |
} |
| 88 |
|