ListResource::setProperty()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DigitalCz\DigiSign\Resource;
6
7
/**
8
 * @template T
9
 */
10
class ListResource extends BaseResource
11
{
12
    /** @var array<T> */
13
    public $items;
14
15
    /** @var int */
16
    public $count;
17
18
    /** @var int */
19
    public $page;
20
21
    /** @var int */
22
    public $itemsPerPage;
23
24
    /** @var class-string<T> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
25
    protected $resourceClass;
26
27
    /**
28
     * @param mixed[] $result
29
     * @param class-string<T> $resourceClass
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
30
     */
31
    public function __construct(array $result, string $resourceClass)
32
    {
33
        $this->resourceClass = $resourceClass;
34
35
        parent::__construct($result);
36
    }
37
38
    /** @inheritDoc */
39
    public function toArray(): array
40
    {
41
        $values = parent::toArray();
42
43
        unset($values['resourceClass']);
44
        $values['items'] = array_map(
45
            static function (BaseResource $item): array {
46
                return $item->toArray();
47
            },
48
            ($values['items'] ?? [])
49
        );
50
51
        return $values;
52
    }
53
54
    /** @inheritDoc */
55
    protected function setProperty(string $property, $value): void
56
    {
57
        if ($property === 'items') {
58
            $resourceClass = $this->resourceClass;
59
            $value = array_map(
60
                static function (array $itemValues) use ($resourceClass): BaseResource {
61
                    return new $resourceClass($itemValues);
62
                },
63
                $value
64
            );
65
        }
66
67
        parent::setProperty($property, $value);
68
    }
69
}
70