Passed
Push — main ( 02be03...8407ab )
by Sammy
02:05
created

Element::isVoid()   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 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace HexMakina\Marker;
4
5
class Element
6
{
7
    const VOID_ELEMENTS = [
8
      'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
9
      'link', 'meta', 'param', 'source', 'track', 'wbr'
10
    ];
11
12
    protected $tagName = '';
13
    protected $attributeList = [];
14
    protected $classList = [];
15
    protected $innerContent = '';
16
17
    public function isVoid()
18
    {
19
        return in_array($this->tagName, self::VOID_ELEMENTS);
20
    }
21
22
    public function __construct($tagName, $innerContent = null, $attributeList = [])
23
    {
24
        $this->tagName = $tagName;
25
        $this->attributeList = $attributeList;
26
        $this->innerContent = $innerContent ?? '';
27
    }
28
29
    private function formatAttributes()
30
    {
31
        $ret = '';
32
33
        foreach ($this->attributeList as $k => $v) {
34
            if (!is_null($v) && $v !== '' && !is_array($v)) {
35
                $ret .=  is_int($k) ? " $v" : sprintf(' %s="%s"', $k, $v);
36
            }
37
        }
38
39
        return $ret;
40
    }
41
42
    public function __toString()
43
    {
44
        $flattributes = $this->formatAttributes();
45
46
        $ret = '';
47
        if ($this->isVoid()) {
48
            $ret = sprintf('<%s%s/>', $this->tagName, $flattributes);
49
        } else {
50
            $ret = sprintf(
51
                '<%s%s>%s</%s>',
52
                $this->tagName,
53
                $flattributes,
54
                $this->innerContent,
55
                $this->tagName
56
            );
57
        }
58
59
        return $ret;
60
    }
61
}
62