Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
5 / 5 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
| Serializable | |
100.00% |
5 / 5 |
|
100.00% |
5 / 5 |
5 | |
100.00% |
1 / 1 |
| toArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| arraySerialize | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| jsonSerialize | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| toJson | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| automaticallySerialize | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Hyde\Support\Concerns; |
| 6 | |
| 7 | use function json_encode; |
| 8 | use function collect; |
| 9 | |
| 10 | /** |
| 11 | * Automatically serializes an Arrayable implementation when JSON is requested. |
| 12 | * |
| 13 | * @see \Hyde\Support\Contracts\SerializableContract |
| 14 | */ |
| 15 | trait Serializable |
| 16 | { |
| 17 | /** Default implementation to dynamically serialize all public properties. Can be overridden for increased control. */ |
| 18 | public function toArray(): array |
| 19 | { |
| 20 | return $this->automaticallySerialize(); |
| 21 | } |
| 22 | |
| 23 | /** Recursively serialize Arrayables */ |
| 24 | public function arraySerialize(): array |
| 25 | { |
| 26 | return collect($this->toArray())->toArray(); |
| 27 | } |
| 28 | |
| 29 | /** @inheritDoc */ |
| 30 | public function jsonSerialize(): array |
| 31 | { |
| 32 | return $this->arraySerialize(); |
| 33 | } |
| 34 | |
| 35 | /** @param int $options */ |
| 36 | public function toJson($options = 0): string |
| 37 | { |
| 38 | return json_encode($this->jsonSerialize(), $options); |
| 39 | } |
| 40 | |
| 41 | /** Automatically serialize all public properties. */ |
| 42 | protected function automaticallySerialize(): array |
| 43 | { |
| 44 | // Calling the function from a different scope means we only get the public properties. |
| 45 | |
| 46 | return get_object_vars(...)->__invoke($this); |
| 47 | } |
| 48 | } |