HasAttributes::setAttributes()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 3
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace JoaoRobertoPB\Htmlable\Traits;
4
5
trait HasAttributes
6
{
7
    /**
8
    * @var array
9
    */
10
    protected $attributes = [];
11
12
    /**
13
    * @param array $attributes
14
    *
15
    * @return $this
16
    */
17 33
    public function setAttributes($attributes)
18
    {
19 33
        foreach ($attributes as $attribute => $value) {
20 12
            if (is_int($attribute)) {
21 3
                $attribute = $value;
22 3
                $value = '';
23 2
            }
24
25 12
            $this->setAttribute($attribute, $value);
26 22
        }
27
28 33
        return $this;
29
    }
30
31
    /**
32
    * @param string $attribute
33
    * @param string $value
34
    *
35
    * @return $this
36
    */
37 18
    public function setAttribute($attribute, $value)
38
    {
39 18
        $this->attributes[$attribute] = $value;
40
41 18
        return $this;
42
    }
43
44
    /**
45
    * @return boolean
46
    */
47 33
    public function attributesIsEmpty()
48
    {
49 33
        return empty($this->attributes);
50
    }
51
52
    /**
53
    * @return array
54
    */
55 18
    public function getAttributes()
56
    {
57 18
        return $this->attributes;
58
    }
59
60
    /**
61
    * @return string
62
    */
63 18
    public function attributesToString()
64
    {
65 18
        if ($this->attributesIsEmpty()) {
66
            return '';
67
        }
68
69 18
        $attributeStrings = [];
70 18
        foreach ($this->getAttributes() as $attribute => $value) {
71 18
            if (is_null($value) || $value === '') {
72 3
                $attributeStrings[] = $attribute;
73 3
                continue;
74
            }
75
76 15
            $attributeStrings[] = "{$attribute}=\"{$value}\"";
77 12
        }
78
79 18
        return implode(' ', $attributeStrings);
80
    }
81
82
    /**
83
    * @return void
84
    */
85 6
    public function __set($attribute, $value)
86
    {
87 6
        $this->setAttribute($attribute, $value);
88 6
    }
89
90
    /**
91
    * @return string
92
    */
93
    public function __get($attribute)
94
    {
95
        if (isset($this->attributes[$attribute])) {
96
            return $this->attributes[$attribute];
97
        }
98
    }
99
100
    /**
101
    * @return bool
102
    */
103
    public function __isset($attribute)
104
    {
105
        return isset($this->attributes[$attribute]);
106
    }
107
108
    /**
109
    * @return void
110
    */
111
    public function __unset($attribute)
112
    {
113
        unset($this->attributes[$attribute]);
114
    }
115
}
116