ArrayValueParser::setRaw()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Aleksandar Panic
4
 * @license http://www.apache.org/licenses/LICENSE-2.0
5
 * @since 1.0.0
6
 **/
7
8
namespace ArekX\ArrayExpression\ValueParsers;
9
10
use ArekX\ArrayExpression\Exceptions\InvalidValueTypeException;
11
12
/**
13
 * Class ArrayValueParser
14
 * Array value parser which parses arrays by specified keys.
15
 *
16
 * @package ArekX\ArrayExpression\ValueParsers
17
 *
18
 */
19
class ArrayValueParser extends BaseValueParser
20
{
21
    protected $valueCache = [];
22
23
    /**
24
     * Sets raw array value to be parsed.
25
     *
26
     * @param mixed $rawValue Array value to be parsed
27
     * @throws InvalidValueTypeException Error which is thrown if raw value is not an array.
28
     */
29 21
    public function setRaw($rawValue)
30
    {
31 21
        if (!is_array($rawValue)) {
32 1
            throw new InvalidValueTypeException($rawValue);
33
        }
34
35 20
        $this->valueCache = [];
36 20
        parent::setRaw($rawValue);
37 20
    }
38
39
40
    /**
41
     * Returns parsed value by specified by $requested name.
42
     *
43
     * If a $requestedName is an empty string whole raw value is returned.
44
     * If a $requestedName is a string in dot notation then array will be traversed to find value from those keys.
45
     *
46
     * @param string $requestedName Requested key to be returned
47
     * @param mixed $default Default value to be returned if nothing is found.
48
     * @return mixed
49
     */
50 17
    public function getValue($requestedName = '', $default = null)
51
    {
52 17
        if ($requestedName === '') {
53 1
            return $this->raw;
54
        }
55
56 16
        if (array_key_exists($requestedName, $this->valueCache)) {
57 1
            return $this->valueCache[$requestedName];
58
        }
59
60 16
        if (is_array($this->raw) && array_key_exists($requestedName, $this->raw)) {
61 11
            return $this->raw[$requestedName];
62
        }
63
64 5
        $parts = explode('.', $requestedName);
65 5
        $walker = $this->raw;
66
67 5
        $lastPart = array_pop($parts);
68
69 5
        foreach ($parts as $part) {
70 5
            if (is_array($walker) && array_key_exists($part, $walker)) {
71 5
                $walker = $walker[$part];
72 5
                continue;
73
            }
74
75 2
            return $this->valueCache[$requestedName] = $default;
76
        }
77
78 3
        if (is_array($walker) && array_key_exists($lastPart, $walker)) {
79 2
            return $this->valueCache[$requestedName] = $walker[$lastPart];
80
        }
81
82 1
        return $this->valueCache[$requestedName] = $default;
83
    }
84
}