Attributes::mergeAttributes()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
namespace rOpenDev\PlatesExtension;
3
4
use League\Plates\Engine;
5
use League\Plates\Extension\ExtensionInterface;
6
7
/**
8
 * Transform an array in html tag attributes
9
 * PSR-2 Coding Style, PSR-4 Autoloading
10
 *
11
 * @author     Robin <[email protected]> http://www.robin-d.fr/
12
 * @link       https://github.com/RobinDev/platesAttributes
13
 * @since      File available since Release 2014.12.15
14
 */
15
class Attributes implements ExtensionInterface
16
{
17
    /**
18
     * @param \League\Plates\Engine $engine
19
     */
20
    public function register(Engine $engine)
21
    {
22
        $engine->registerFunction('mergeAttr', [$this, 'mergeAttributes']);
23
        $engine->registerFunction('attr',      [$this, 'mapAttributes']);
24
    }
25
26
    /**
27
     * It will merge multiple attributes arrays without erase values
28
     *
29
     * @return array
30
     */
31
    public static function mergeAttributes()
32
    {
33
        $arrays = func_get_args();
34
        $result = [];
35
36
        foreach ($arrays as $array) {
37
            $result = self::mergeRecursive($result, $array);
38
        }
39
40
        return $result;
41
    }
42
43
    /**
44
     * @param  array $arr1
45
     * @param  array $arr2
46
     * @return array
47
     */
48
    protected static function mergeRecursive(array $arr1, array $arr2)
49
    {
50
        foreach ($arr2 as $key => $v) {
51
            if (is_array($v)) {
52
                $arr1[$key] = isset($arr1[$key]) ? self::mergeRecursive($arr1[$key], $v) : $v;
53
            }
54
            else {
55
                $arr1[$key] = isset($arr1[$key]) ? $arr1[$key].($arr1[$key] != $v ? ' '.$v : '') : $v;
56
            }
57
        }
58
59
        return $arr1;
60
    }
61
62
    /**
63
     * Render the attributes
64
     *
65
     * @param  array  $attributes
66
     * @return string
67
     */
68
    public static function mapAttributes(array $attributes)
69
    {
70
        $result = '';
71
72
        foreach ($attributes as $attribute => $value) {
73
            $e = strpos($value, ' ') !== false ? '"' : '';
74
            $result .= ' '.(is_int($attribute) ? $value : $attribute.'='.$e.str_replace('"', '&quot;',$value).$e);
75
        }
76
77
        return $result;
78
    }
79
}
80