Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
13 / 13 |
|
100.00% |
6 / 6 |
CRAP | |
100.00% |
1 / 1 |
| BasicResource | |
100.00% |
13 / 13 |
|
100.00% |
6 / 6 |
9 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| collection | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| toArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| toIdentifierArray | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| toJson | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| __toString | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Engelsystem\Controllers\Api\Resources; |
| 6 | |
| 7 | use Engelsystem\Models\BaseModel; |
| 8 | use Illuminate\Contracts\Support\Arrayable; |
| 9 | use Illuminate\Contracts\Support\Jsonable; |
| 10 | use Illuminate\Database\Eloquent\Relations\Pivot; |
| 11 | use Illuminate\Support\Collection; |
| 12 | use Stringable; |
| 13 | |
| 14 | /** @phpstan-consistent-constructor */ |
| 15 | abstract class BasicResource implements Arrayable, Jsonable, Stringable |
| 16 | { |
| 17 | public function __construct(protected Collection | BaseModel | Pivot $model) |
| 18 | { |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * @param iterable|Collection|BaseModel[]|Collection[] $data |
| 23 | */ |
| 24 | public static function collection(iterable $data): Collection |
| 25 | { |
| 26 | $collection = new Collection(); |
| 27 | foreach ($data as $item) { |
| 28 | $collection->add(new static($item)); |
| 29 | } |
| 30 | return $collection; |
| 31 | } |
| 32 | |
| 33 | public function toArray(): array |
| 34 | { |
| 35 | return $this->model->toArray(); |
| 36 | } |
| 37 | |
| 38 | public static function toIdentifierArray(array | Arrayable $data): array |
| 39 | { |
| 40 | $data = $data instanceof Arrayable ? $data->toArray() : $data; |
| 41 | $identifier = ['id' => $data['id']]; |
| 42 | if (array_key_exists('name', $data)) { |
| 43 | $identifier['name'] = $data['name']; |
| 44 | } |
| 45 | return $identifier; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * @param int $options |
| 50 | */ |
| 51 | public function toJson($options = 0): string // phpcs:ignore |
| 52 | { |
| 53 | return json_encode($this->toArray(), $options); |
| 54 | } |
| 55 | |
| 56 | public function __toString(): string |
| 57 | { |
| 58 | return $this->toJson(); |
| 59 | } |
| 60 | } |