Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
BasicResource
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
6 / 6
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 collection
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 toArray
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toIdentifierArray
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 toJson
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __toString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Controllers\Api\Resources;
6
7use Engelsystem\Models\BaseModel;
8use Illuminate\Contracts\Support\Arrayable;
9use Illuminate\Contracts\Support\Jsonable;
10use Illuminate\Support\Collection;
11use Stringable;
12
13/** @phpstan-consistent-constructor */
14abstract 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}