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('"', '"',$value).$e); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $result; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|