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\Support\Collection; |
11 | use Stringable; |
12 | |
13 | /** @phpstan-consistent-constructor */ |
14 | abstract class BasicResource implements Arrayable, Jsonable, Stringable |
15 | { |
16 | public function __construct(protected BaseModel | Collection $model) |
17 | { |
18 | } |
19 | |
20 | /** |
21 | * @param iterable|Collection|BaseModel[]|Collection[] $data |
22 | */ |
23 | public static function collection(iterable $data): Collection |
24 | { |
25 | $collection = new Collection(); |
26 | foreach ($data as $item) { |
27 | $collection->add(new static($item)); |
28 | } |
29 | return $collection; |
30 | } |
31 | |
32 | public function toArray(): array |
33 | { |
34 | return $this->model->toArray(); |
35 | } |
36 | |
37 | public static function toIdentifierArray(array | Arrayable $data): array |
38 | { |
39 | $data = $data instanceof Arrayable ? $data->toArray() : $data; |
40 | $identifier = ['id' => $data['id']]; |
41 | if (array_key_exists('name', $data)) { |
42 | $identifier['name'] = $data['name']; |
43 | } |
44 | return $identifier; |
45 | } |
46 | |
47 | /** |
48 | * @param int $options |
49 | */ |
50 | public function toJson($options = 0): string // phpcs:ignore |
51 | { |
52 | return json_encode($this->toArray(), $options); |
53 | } |
54 | |
55 | public function __toString(): string |
56 | { |
57 | return $this->toJson(); |
58 | } |
59 | } |