Element::buildAttribute()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 2
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Jhoff\BladeVue;
4
5
class Element
6
{
7
    /**
8
     * Element tag name
9
     *
10
     * @var string
11
     */
12
    protected $name;
13
14
    /**
15
     * Element attributes
16
     *
17
     * @var array
18
     */
19
    protected $attributes = [];
20
21
    /**
22
     * Instantiate a new element
23
     *
24
     * @param string $name
25
     */
26 13
    public function __construct(string $name)
27
    {
28 13
        $this->name = $name;
29 13
    }
30
31
    /**
32
     * Gets the ending tag for the element
33
     *
34
     * @return string
35
     */
36 6
    public function getEndTag() : string
37
    {
38 6
        return "</{$this->name}>";
39
    }
40
41
    /**
42
     * Gets the starting tag for the element
43
     *
44
     * @return string
45
     */
46 12
    public function getStartTag() : string
47
    {
48 12
        $attributes = $this->renderAttributes();
49
50 12
        return "<{$this->name}" . ($attributes ? ' ' . $attributes : '') . '>';
51
    }
52
53
    /**
54
     * Sets the attribute on the element
55
     *
56
     * @param string $name
57
     * @param mixed $value
58
     * @return $this
59
     */
60 11
    public function setAttribute(string $name, $value)
61
    {
62 11
        $this->attributes[$name] = $value;
63
64 11
        return $this;
65
    }
66
67
    /**
68
     * Builds an attribute string
69
     *
70
     * @param string $key
71
     * @param mixed $value
72
     * @return string
73
     */
74 11
    protected function buildAttribute(string $key, $value) : string
75
    {
76 11
        if (is_numeric($key)) {
77 9
            return $value;
78
        }
79
80 11
        if (is_null($value)) {
81 1
            return $key;
82
        }
83
84 10
        return sprintf('%s="%s"', $key, $value);
85
    }
86
87
    /**
88
     * Renders all of the attributes in the proper format
89
     *
90
     * @return string
91
     */
92 12
    protected function renderAttributes() : string
93
    {
94 12
        return implode(' ', array_map(
95 12
            [$this, 'buildAttribute'],
96 12
            array_keys($this->attributes),
97 12
            $this->attributes
98
        ));
99
    }
100
}
101