Collection.php
61 lines
| 1 | <?php |
| 2 | |
| 3 | //TODO PHP7.x; declare(strict_types=1); |
| 4 | |
| 5 | namespace WPStaging\Framework\Collection; |
| 6 | |
| 7 | use SplObjectStorage; |
| 8 | use JsonSerializable; |
| 9 | use WPStaging\Framework\Interfaces\ArrayableInterface; |
| 10 | use WPStaging\Framework\Interfaces\HydrateableInterface; |
| 11 | |
| 12 | class Collection extends SplObjectStorage implements JsonSerializable |
| 13 | { |
| 14 | /** @var string */ |
| 15 | protected $storedClass; |
| 16 | |
| 17 | /** |
| 18 | * @param string $storedClass |
| 19 | */ |
| 20 | public function __construct($storedClass) |
| 21 | { |
| 22 | $this->storedClass = $storedClass; |
| 23 | } |
| 24 | |
| 25 | public function toArray() |
| 26 | { |
| 27 | $collection = []; |
| 28 | /** @var ArrayableInterface $item */ |
| 29 | foreach ($this as $item) { |
| 30 | if (method_exists($item, 'toArray')) { |
| 31 | $collection[] = $item->toArray(); |
| 32 | } else { |
| 33 | $collection[] = $item; |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | return $collection; |
| 38 | } |
| 39 | |
| 40 | public function attachAllByArray(array $data = []) |
| 41 | { |
| 42 | foreach ($data as $item) { |
| 43 | if ($item instanceof $this->storedClass) { |
| 44 | $this->attach($item); |
| 45 | continue; |
| 46 | } |
| 47 | |
| 48 | /** @var HydrateableInterface $object */ |
| 49 | $object = new $this->storedClass(); |
| 50 | $object->hydrate((array) $item); |
| 51 | $this->attach($object); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | #[\ReturnTypeWillChange] |
| 56 | public function jsonSerialize() |
| 57 | { |
| 58 | return $this->toArray(); |
| 59 | } |
| 60 | } |
| 61 |