Test Failed
Push — master ( d818fc...2d2f9a )
by Christophe
08:50
created

AbstractOptionsOutput::renameRecursivelyKeys()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 13
nc 5
nop 1
1
<?php
2
3
namespace CMEN\GoogleChartsBundle\Output;
4
5
use CMEN\GoogleChartsBundle\GoogleCharts\Options\ChartOptionsInterface;
6
7
/**
8
 * @author Christophe Meneses
9
 */
10
abstract class AbstractOptionsOutput implements OptionsOutputInterface
11
{
12
    /**
13
     * Removes recursively array elements that have a null value.
14
     *
15
     * @param ChartOptionsInterface|array $options ChartOptions instance or an array of options passed by reference
16
     */
17
    public function removeRecursivelyNullValue(&$options)
18
    {
19
        $options = array_filter((array) $options, function ($val) {
20
            return !is_null($val);
21
        });
22
23
        foreach ($options as $key => $value) {
24
            if (is_object($value) || is_array($value)) {
25
                $this->removeRecursivelyNullValue($options[$key]);
26
            }
27
        }
28
    }
29
30
    /**
31
     * Removes recursively array elements that have an empty array.
32
     *
33
     * @param array $options Array of options passed by reference
34
     */
35
    public function removeRecursivelyEmptyArray(&$options)
36
    {
37
        foreach ($options as $key => $value) {
38
            if (is_array($value)) {
39
                $this->removeRecursivelyEmptyArray($options[$key]);
40
41
                if (empty($options[$key])) {
42
                    unset($options[$key]);
43
                }
44
            }
45
        }
46
    }
47
48
    /**
49
     * Renames recursively array keys to remove prefixes and suffixes "\x00". They come from conversion of class with
50
     * protected properties to an array.
51
     *
52
     * @param array $options Array of options
53
     *
54
     * @return array Array of options with new keys
55
     */
56
    public function renameRecursivelyKeys($options)
57
    {
58
        $newOptions = [];
59
60
        foreach ($options as $key => $value) {
61
            if (!is_numeric($key)) {
62
                $newKey = preg_replace('/\x00\*\x00/', '', $key);
63
                $newOptions[$newKey] = $value;
64
65
                if (is_array($options[$key])) {
66
                    $newOptions[$newKey] = $this->renameRecursivelyKeys($options[$key]);
67
                }
68
            } else {
69
                $newOptions[$key] = $value;
70
71
                if (is_array($options[$key])) {
72
                    $newOptions[$key] = $this->renameRecursivelyKeys($options[$key]);
73
                }
74
            }
75
        }
76
77
        return $newOptions;
78
    }
79
}
80