HtmlClassHelper::hasStringKeys()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
ccs 3
cts 3
cp 1
rs 9.6666
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @copyright Zicht Online
4
 */
5
namespace Zicht;
6
7
/**
8
 * Utility class for generating CSS class names based on supplied predicates.
9
 */
10
class HtmlClassHelper
11
{
12
    /**
13
     * Builds a string of CSS class names based on supplied predicates.
14
     *
15
     * @param array ...$config
16
     * @return string
17
     */
18 12
    public static function getClasses(...$config)
19
    {
20 12
        $classes = [];
21
22 12
        foreach ($config as $argument) {
23 12
            $classes = self::addArgumentToClasses($classes, $argument);
24 12
        }
25
26 12
        return join('  ', $classes);
27
    }
28
29
    /**
30
     * Helper function that determines whether the supplied classes should
31
     * be added, according to the supplied argument.
32
     *
33
     * @param array $classes
34
     * @param string|array $argument
35
     * @return array
36
     */
37 12
    private static function addArgumentToClasses($classes, $argument)
38
    {
39 12
        switch (gettype($argument))
40
        {
41 12
            case 'string':
42 4
                array_push($classes, $argument);
43 4
                break;
44 10
            case 'array':
45 9
                if (!self::hasStringKeys($argument)) {
46 3
                    $classes = array_merge($classes, $argument);
47 3
                    break;
48
                }
49
50 6
                foreach ($argument as $class => $predicate) {
51 6
                    if (!$predicate) {
52 4
                        continue;
53
                    }
54
55 4
                    array_push($classes, $class);
56 6
                }
57 6
                break;
58
59 1
            default:
60 1
                break;
61 12
        }
62
63 12
        return $classes;
64
    }
65
66
67
    /**
68
     * Determines whether an array has string keys.
69
     *
70
     * @param array $array
71
     * @return bool
72
     */
73 9
    private static function hasStringKeys($array)
74
    {
75 9
        $keys = array_keys($array);
76
77
        /**
78
         * If the array keys of the keys match the keys, then the array must not be associative.
79
         */
80 9
        return array_keys($keys) !== $keys;
81
    }
82
}
83