SchemaArrayAttribute   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 24
c 2
b 0
f 0
dl 0
loc 64
rs 10
wmc 14

6 Methods

Rating   Name   Duplication   Size   Complexity  
A parseContextual() 0 14 4
A getArrayDefinitionString() 0 4 1
A serialize() 0 18 5
A getGenericDefinitionString() 0 3 2
A from() 0 3 1
A __construct() 0 4 1
1
<?php
2
3
namespace Ipag\Sdk\Model\Schema;
4
5
use Ipag\Sdk\Model\Schema\Exception\SchemaAttributeParseException;
6
use Ipag\Sdk\Model\Schema\Exception\SchemaAttributeSerializeException;
7
8
/**
9
 * @codeCoverageIgnore
10
 */
11
class SchemaArrayAttribute extends SchemaAttribute
12
{
13
    protected SchemaAttribute $childrenSchema;
14
15
    public function __construct(Schema $schema, string $name, ?SchemaAttribute $childrenSchema = null)
16
    {
17
        parent::__construct($schema, $name);
18
        $this->childrenSchema = $childrenSchema;
19
    }
20
21
    public function parseContextual($value)
22
    {
23
        if (is_iterable($value)) {
24
            if (!is_array($value)) {
25
                $value = iterator_to_array($value);
26
            }
27
        }
28
29
        if (is_array($value)) {
30
            return array_map(fn($v) => $this->childrenSchema->parse($v), $value);
31
        }
32
33
        $arrayDefinition = $this->getArrayDefinitionString();
34
        throw new SchemaAttributeParseException($this, "Provided value is not a valid {$arrayDefinition}");
35
    }
36
37
    public function serialize($value)
38
    {
39
        if (is_null($value)) {
40
            return null;
41
        }
42
43
        if (is_iterable($value)) {
44
            if (!is_array($value)) {
45
                $value = iterator_to_array($value);
46
            }
47
48
            return array_map(
49
                fn($serializable) => $this->childrenSchema ? $this->childrenSchema->serialize($serializable) : $serializable,
50
                $value
51
            );
52
        }
53
54
        throw new SchemaAttributeSerializeException($this, "Provided value is not a valid array to be serialized");
55
    }
56
57
    //
58
59
    private function getGenericDefinitionString(): string
60
    {
61
        return $this->childrenSchema ? $this->childrenSchema->getType() : '*';
62
    }
63
64
    private function getArrayDefinitionString(): string
65
    {
66
        $childrenType = $this->getGenericDefinitionString();
67
        return "array<{$childrenType}>";
68
    }
69
70
    //
71
72
    public static function from(Schema $schema, string $name, ?SchemaAttribute $childrenSchema = null): self
73
    {
74
        return new self($schema, $name, $childrenSchema);
75
    }
76
}