| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPIDE\App\Utils; |
| 4 |
|
| 5 |
trait Collection |
| 6 |
{ |
| 7 |
protected $items = []; |
| 8 |
|
| 9 |
public function add($obj) |
| 10 |
{ |
| 11 |
return $this->items[] = $obj; |
| 12 |
} |
| 13 |
|
| 14 |
public function delete($obj) |
| 15 |
{ |
| 16 |
foreach ($this->items as $key => $item) { |
| 17 |
if ($item === $obj) { |
| 18 |
unset($this->items[$key]); |
| 19 |
} |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
public function all(): array |
| 24 |
{ |
| 25 |
return $this->items; |
| 26 |
} |
| 27 |
|
| 28 |
public function get($id, $key = 'id'): array |
| 29 |
{ |
| 30 |
return array_filter( $this->items, function($item) use (&$id, &$key) { |
| 31 |
return $item[$key] == $id; |
| 32 |
}); |
| 33 |
} |
| 34 |
|
| 35 |
public function length(): int |
| 36 |
{ |
| 37 |
return count($this->items); |
| 38 |
} |
| 39 |
|
| 40 |
public function jsonSerialize(): array |
| 41 |
{ |
| 42 |
return $this->items; |
| 43 |
} |
| 44 |
|
| 45 |
public function filter(callable $callback) |
| 46 |
{ |
| 47 |
$this->items = array_filter($this->items, $callback); |
| 48 |
|
| 49 |
return $this; |
| 50 |
} |
| 51 |
|
| 52 |
public function map(callable $callback) |
| 53 |
{ |
| 54 |
$this->items = array_map($callback, $this->items); |
| 55 |
|
| 56 |
return $this; |
| 57 |
} |
| 58 |
|
| 59 |
public function merge($collection) { |
| 60 |
|
| 61 |
$this->items = array_merge($this->items, $collection->items); |
| 62 |
} |
| 63 |
|
| 64 |
public function sortByValue($value, $desc = false) |
| 65 |
{ |
| 66 |
usort($this->items, function ($a, $b) use ($value) { |
| 67 |
return $a[$value] <=> $b[$value]; |
| 68 |
}); |
| 69 |
|
| 70 |
if ($desc) { |
| 71 |
$this->items = array_reverse($this->items); |
| 72 |
} |
| 73 |
|
| 74 |
return $this; |
| 75 |
} |
| 76 |
} |
| 77 |
|