Completed
Push — master ( 97bc30...8f50f7 )
by Pol
09:42 queued 06:23
created

AbstractBaseHtmlTagObject::ensureFlatArray()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace drupol\htmltag;
4
5
/**
6
 * Class AbstractBaseHtmlTagObject
7
 */
8
abstract class AbstractBaseHtmlTagObject
9
{
10
    /**
11
     * Normalize a value.
12
     *
13
     * @param mixed $values
14
     *  The value to normalize.
15
     *
16
     * @return array
17
     *   The value normalized.
18
     */
19 23
    protected function normalizeValue($values)
20
    {
21 23
        return array_unique(
22 23
            array_reduce(
23 23
                array_map(
24 23
                    array($this, 'ensureArray'),
25 23
                    $this->ensureFlatArray($this->ensureArray($values))
26
                ),
27 23
                'array_merge',
28 23
                []
29
            )
30
        );
31
    }
32
33
    /**
34
     * Transform a multidimensional array into a flat array.
35
     *
36
     * @param mixed[] $array
37
     *   The input array.
38
     *
39
     * @return mixed[]
40
     *   The array with only one dimension.
41
     */
42 27
    protected function ensureFlatArray(array $array)
43
    {
44 27
        return array_reduce(
45 27
            $array,
46
            function ($carry, $item) {
47 23
                return is_array($item) ?
48 23
                    array_merge($carry, $this->ensureFlatArray($item)) :
49 23
                    array_merge($carry, [$item]);
50 27
            },
51 27
            []
52
        );
53
    }
54
55
    /**
56
     * Make sure the value is an array.
57
     *
58
     * @param mixed $value
59
     *   The input value.
60
     *
61
     * @return array
62
     *   The input value in an array.
63
     */
64 27
    protected function ensureArray($value)
65
    {
66 27
        $return = null;
67
68 27
        switch (gettype($value)) {
69 27
            case 'array':
70 23
                return $value;
71 26
            case 'string':
72 21
                $return = $value;
73 21
                break;
74 15
            case 'integer':
75 14
            case 'double':
76 2
                $return = (string) $value;
77 2
                break;
78 14
            case 'object':
79 1
                if (method_exists($value, '__toString')) {
80
                    $return = (string) $value;
81
                }
82 1
                break;
83 14
            case 'boolean':
84 1
                if (true === $value) {
85 1
                    $return = '';
86
                }
87 1
                break;
88
        }
89
90 26
        return null === $return ?
91 14
            []:
92 26
            explode(' ', preg_replace('!\s+!', ' ', trim(addcslashes($return, '\"'))));
93
    }
94
}
95