Passed
Push — master ( 689ec5...45f08c )
by Sebastian
05:26
created

AttributesRenderer::compileAttributes()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 17
rs 10
cc 3
nc 4
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AppUtils\AttributeCollection;
6
7
use AppUtils\AttributeCollection;
8
9
class AttributesRenderer
10
{
11
    /**
12
     * @var AttributeCollection
13
     */
14
    private $collection;
15
16
    public function __construct(AttributeCollection $collection)
17
    {
18
        $this->collection = $collection;
19
    }
20
21
    public function render() : string
22
    {
23
        $list = array();
24
25
        $attributes = $this->compileAttributes();
26
27
        if(empty($attributes))
28
        {
29
            return '';
30
        }
31
32
        foreach($attributes as $name => $value)
33
        {
34
            if($value === '')
35
            {
36
                continue;
37
            }
38
39
            $list[] = $this->renderAttribute($name, $value);
40
        }
41
42
        return ' '.implode(' ', $list);
43
    }
44
45
    /**
46
     * Compiles all attributes, including the dynamic ones,
47
     * into an associative array with attribute name => value
48
     * pairs.
49
     *
50
     * @return array<string,string>
51
     */
52
    public function compileAttributes() : array
53
    {
54
        $attributes = $this->collection->getRawAttributes();
55
56
        if($this->collection->hasClasses())
57
        {
58
            $attributes['class'] = $this->collection->classesToString();
59
        }
60
61
        if($this->collection->hasStyles())
62
        {
63
            $attributes['style'] = $this->collection->getStyles()
64
                ->configureForInline()
65
                ->render();
66
        }
67
68
        return $attributes;
69
    }
70
71
    private function renderAttribute(string $name, string $value) : string
72
    {
73
        if($name === $value)
74
        {
75
            return $name;
76
        }
77
78
        return sprintf(
79
            '%s="%s"',
80
            $name,
81
            $value
82
        );
83
    }
84
}
85