Passed
Push — master ( bb4653...2ab0f7 )
by Bruno
07:17
created

Metadata::toGraphql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 0
dl 0
loc 18
rs 9.8666
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Formularium;
4
5
/**
6
 * Class to store information about a validator, datatype, renderable or element
7
 * and its parameters.
8
 */
9
final class Metadata
10
{
11
    /**
12
     * @var string
13
     */
14
    public $name;
15
16
    /**
17
     * @var string
18
     */
19
    public $comment;
20
21
    /**
22
     * @var MetadataParameter[]
23
     */
24
    public $args;
25
26
    public function __construct(string $name, string $comment, array $args = [])
27
    {
28
        $this->name = $name;
29
        $this->comment = $comment;
30
        $this->args = $args;
31
    }
32
33
    public function appendParameter(MetadataParameter $p): self
34
    {
35
        $this->args[] = $p;
36
        return $this;
37
    }
38
39
    public function toMarkdown(): string
40
    {
41
        $args = array_map(
42
            function (MetadataParameter $a) {
43
                return $a->toMarkdown();
44
            },
45
            $this->args
46
        );
47
48
        $argString = '';
49
        if (!empty($args)) {
50
            $argString = join("\n", $args);
51
        }
52
53
        return <<<EOF
54
## {$this->name}
55
56
{$this->comment}
57
58
$argString
59
60
EOF;
61
    }
62
63
    public function toGraphql(): string
64
    {
65
        $args = array_map(
66
            function (MetadataParameter $a) {
67
                return $a->toGraphql();
68
            },
69
            $this->args
70
        );
71
72
        $argString = '';
73
        if (!empty($args)) {
74
            $argString = "(" . join("\n", $args) . "\n)";
75
        }
76
        return <<< EOF
77
"""
78
{$this->comment}
79
"""
80
directive @{$this->name}{$argString} on FIELD_DEFINITION
81
82
EOF;
83
    }
84
85
    public function hasParameter(string $name): bool
86
    {
87
        foreach ($this->args as $a) {
88
            if ($a->name === $name) {
89
                return true;
90
            }
91
        }
92
        return false;
93
    }
94
95
    public function parameter(string $name): ?MetadataParameter
96
    {
97
        foreach ($this->args as $a) {
98
            if ($a->name === $name) {
99
                return $a;
100
            }
101
        }
102
        return null;
103
    }
104
}
105