Passed
Branch develop (612b6d)
by Steve
04:05
created

RecursiveTransform::shouldTransformValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace StoutLogic\AcfBuilder\Transform;
4
5
/**
6
 * Transform applies to all leafs in array, at specific keys
7
 * using array_walk_recursive
8
 */
9
abstract class RecursiveTransform extends Transform
10
{
11
    /**
12
     * Define a list of array keys `transformValue` should apply to.
13
     * @var array
14
     */
15
    protected $keys = [];
16
17
    /**
18
     * @return array
19
     */
20
    public function getKeys()
21
    {
22
        return $this->keys;
23
    }
24
25
    /**
26
     * Apply the `transformValue` function to all values in multidementional
27
     * associative array where the key matches one of the keys defined
28
     * on the RecursiveTransform.
29
     * @param  array $config
30
     * @return array transformed config
31
     */
32
    public function transform($config)
33
    {
34
        foreach ($config as $key => $value ) {
35
            if ($this->shouldTransformValue($key, $config)) {
36
                $config = $this->transformConfig($config);
37
                $config[$key] = $this->transformValue($value);
38
            } else {
39
                if ($this->shouldRecurse($value, $key)) {
40
                    $config[$key] = $this->transform($value);
41
                }
42
            }
43
        }
44
45
        return $config;
46
    }
47
48
49
    /**
50
     * @param string $key
51
     * @param array $config
52
     * @return bool
53
     */
54
    public function shouldTransformValue($key, $config)
55
    {
56
        return in_array($key, $this->getKeys(), true);
57
    }
58
59
    /**
60
     * Based upon the value or key, determine if the transform function
61
     * should recurse.
62
     * @param $value
63
     * @param string $key
64
     * @return bool
65
     */
66
    protected function shouldRecurse($value, $key)
67
    {
68
        return is_array($value);
69
    }
70
71
    /**
72
     * Impelment this in all discrete classes
73
     * @param  mixed $value input
74
     * @return mixed output value
75
     */
76
    abstract public function transformValue($value);
77
78
79
    /**
80
     * @param array $config
81
     * @return array
82
     */
83
    public function transformConfig($config)
84
    {
85
        return $config;
86
    }
87
}
88