Passed
Push — main ( 21e8dc...62d82d )
by Pavel
01:31
created

Fieldset::hasFieldset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php namespace JSONAPI\Resource;
2
3
/**
4
 * Class simplifies the work with the JSON:API fields sets.
5
 *
6
 * Can be accessed as an array.
7
 * Key is an resource type and value is array with allowed fields list.
8
 *
9
 * @link https://jsonapi.org/format/#fetching-sparse-fieldsets
10
 *
11
 * @implements \ArrayAccess<string, string[]>
12
 * @implements \IteratorAggregate<string, string[]>
13
 */
14
final class Fieldset implements \ArrayAccess, \IteratorAggregate
15
{
16
    const SEPARATOR = ',';
17
18
    /** @var array<string, string[]>  */
19
    protected array $fieldSet = [];
20
21
    /**
22
     * @param array<string, string[]|string> $fieldSet
23
     */
24
    public function __construct(array $fieldSet = [])
25
    {
26
        foreach (array_keys($fieldSet) as $type) {
27
            if (!is_string($type)) {
28
                throw new \InvalidArgumentException('Provided fieldset key is not a string.');
29
            }
30
31
            if (is_string($fieldSet[$type])) {
32
                $fieldSet[$type] = explode(static::SEPARATOR, $fieldSet[$type]);
33
            }
34
35
            if (!is_array($fieldSet[$type])) {
36
                throw new \InvalidArgumentException(sprintf(
37
                    'Provided fieldset value for type "%s" is not string and not array.',
38
                    $type
39
                ));
40
            }
41
        }
42
43
        $this->fieldSet = $fieldSet;
44
    }
45
46
    public function hasFieldset(string $type): bool
47
    {
48
        return isset($this[$type]);
49
    }
50
51
    public function offsetExists($key)
52
    {
53
        return isset($this->fieldSet[$key]);
54
    }
55
56
    public function offsetGet($key)
57
    {
58
        return isset($this->fieldSet[$key]) ? $this->fieldSet[$key] : null;
59
    }
60
61
    public function offsetSet($key, $value)
62
    {
63
        throw new \LogicException('Modifying fieldset is not permitted');
64
    }
65
66
    public function offsetUnset($key)
67
    {
68
        throw new \LogicException('Modifying fieldset is not permitted');
69
    }
70
71
    public function getIterator()
72
    {
73
        return new \ArrayIterator($this->fieldSet);
74
    }
75
}