Passed
Push — master ( a7050c...f62674 )
by Bruno
10:03
created

ExtradataTrait::getExtradataSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 11
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 18
rs 9.9
1
<?php declare(strict_types=1);
2
3
namespace Formularium;
4
5
trait ExtradataTrait
6
{
7
    /**
8
     * @var Extradata[]
9
     */
10
    protected $extradata = [];
11
12
    public function setExtradata(array $data)
13
    {
14
        $this->extradata = [];
15
        foreach ($data as $d) {
16
            $this->extradata[] = ($d instanceof Extradata) ? $d : Extradata::getFromData(null, $d);
17
        }
18
    }
19
20
    /**
21
     * All extradata objects. Yeah, that's a horrible plural, I know.
22
     *
23
     * @return Extradata[]
24
     */
25
    public function getExtradatas(): array
26
    {
27
        return $this->extradata;
28
    }
29
30
    public function getExtradataSerialize(): array
31
    {
32
        return array_map(
33
            function (Extradata $e) {
34
                return [
35
                    'name' => $e->getName(),
36
                    'args' => array_map(
37
                        function (ExtradataParameter $a) {
38
                            return [
39
                                'name' => $a->name,
40
                                'value' => $a->value
41
                            ];
42
                        },
43
                        $e->args
44
                    )
45
                ];
46
            },
47
            $this->extradata
48
        );
49
    }
50
51
    /**
52
     * @param string $name
53
     * @return Extradata
54
     */
55
    public function getExtradata(string $name)
56
    {
57
        foreach ($this->extradata as $m) {
58
            if ($m->getName() === $name) {
59
                return $m;
60
            }
61
        }
62
        return null;
63
    }
64
65
    /**
66
     * @param string $name
67
     * @param string $parameter
68
     * @param Mixed $default
69
     * @return Mixed
70
     */
71
    public function getExtradataValue(string $name, string $parameter, $default = null)
72
    {
73
        $e = $this->getExtradata($name);
74
        if (!$e) {
0 ignored issues
show
introduced by
$e is of type Formularium\Extradata, thus it always evaluated to true.
Loading history...
75
            return $default;
76
        }
77
        return $e->value($parameter, $default);
78
    }
79
80
    public function appendExtradata(Extradata $m): self
81
    {
82
        $this->extradata[] = $m;
83
        return $this;
84
    }
85
}
86