1 <?php
2
3 /*
4 * This file is part of the Brickrouge package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Brickrouge;
13
14 /**
15 * Renders CSS class names into a string suitable for the HTML `class` attribute.
16 *
17 * <pre>
18 * <?php
19 *
20 * namespace Brickrouge;
21 *
22 * $class_names = array
23 * (
24 * 'node-id' => 'node-id-13',
25 * 'node-slug' => 'node-slug-example',
26 * 'is-active' => true,
27 * 'is-disabled' => false
28 * );
29 *
30 * echo render_css_class($class_names); // "node-id-13 node-slug-example is-active"
31 * echo render_css_class($class_names, array('node-id', 'is-active')); // "node-id-13 is-active"
32 * echo render_css_class($class_names, 'node-id is-active'); // "node-id-13 is-active"
33 * echo render_css_class($class_names, '-node-slug'); // "node-id-13 is-active"
34 * </pre>
35 *
36 * @param array $names CSS class names.
37 * @param string|array $modifiers CSS class names modifiers.
38 *
39 * @return string
40 */
41 function render_css_class(array $names, $modifiers=null)
42 {
43 $names = array_filter($names);
44
45 if ($modifiers)
46 {
47 if (is_string($modifiers))
48 {
49 $modifiers = explode(' ', $modifiers);
50 }
51
52 $modifiers = array_map('trim', $modifiers);
53 $modifiers = array_filter($modifiers);
54
55 foreach ($modifiers as $k => $modifier)
56 {
57 if ($modifier{0} == '-')
58 {
59 unset($names[substr($modifier, 1)]);
60 unset($modifiers[$k]);
61 }
62 }
63
64 if ($modifiers)
65 {
66 $names = array_intersect_key($names, array_combine($modifiers, $modifiers));
67 }
68 }
69
70 array_walk($names, function(&$v, $k) {
71
72 if ($v === true) $v = $k;
73
74 });
75
76 return implode(' ', $names);
77 }