AttributesTrait::mapAttributes()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 14
rs 9.6111
1
<?php
2
3
namespace PiedWeb\RenderAttributes;
4
5
/**
6
 * Transform an array in html tag attributes
7
 * PSR-2 Coding Style, PSR-4 Autoloading.
8
 *
9
 * @author     Robin <[email protected]> https://piedweb.com
10
 *
11
 * @see       https://github.com/RobinDev/platesAttributes
12
 * @since      File available since Release 2014.12.15
13
 */
14
trait AttributesTrait
15
{
16
    /**
17
     * Merge multiple attributes arrays without erase values.
18
     *
19
     * @return array
20
     */
21
    public static function mergeAttributes()
22
    {
23
        $arrays = \func_get_args();
24
        $result = [];
25
26
        foreach ($arrays as $array) {
27
            $result = self::mergeRecursive($result, $array);
28
        }
29
30
        return $result;
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    protected static function mergeRecursive(array $arr1, array $arr2)
37
    {
38
        foreach ($arr2 as $key => $v) {
39
            if (\is_array($v)) {
40
                $arr1[$key] = isset($arr1[$key]) ? self::mergeRecursive($arr1[$key], $v) : $v;
41
            } else {
42
                $arr1[$key] = isset($arr1[$key]) ? $arr1[$key].($arr1[$key] != $v ? ' '.$v : '') : $v;
43
            }
44
        }
45
46
        return $arr1;
47
    }
48
49
    /**
50
     * Render the attributes.
51
     *
52
     * @return string
53
     */
54
    public static function mapAttributes(array $attributes)
55
    {
56
        $result = '';
57
58
        foreach ($attributes as $attribute => $value) {
59
            if (empty($value)) {
60
                $result .= ' '.$attribute;
61
            } else {
62
                $e = false !== strpos($value, ' ') ? '"' : '';
63
                $result .= ' '.(\is_int($attribute) ? $value : $attribute.'='.$e.str_replace('"', '&quot;', $value).$e);
64
            }
65
        }
66
67
        return $result;
68
    }
69
70
    /**
71
     * Merge and Map.
72
     *
73
     * @return string
74
     */
75
    public static function mergeAndMapAttributes()
76
    {
77
        $arrays = \func_get_args();
78
        $result = [];
79
80
        foreach ($arrays as $array) {
81
            $result = self::mergeRecursive($result, $array);
82
        }
83
84
        return self::mapAttributes($result);
85
    }
86
}
87