ObjectValueParser::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 ObjectValueParser
14
 * Object value parser which parses objects via keys.
15
 *
16
 * @package ArekX\ArrayExpression\ValueParsers
17
 *
18
 */
19
class ObjectValueParser 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 10
    public function setRaw($rawValue)
30
    {
31 10
        if (!is_object($rawValue)) {
32 1
            throw new InvalidValueTypeException($rawValue);
33
        }
34
35 9
        $this->valueCache = [];
36 9
        parent::setRaw($rawValue);
37 9
    }
38
39
    /**
40
     * Returns parsed value by specified by $requested name.
41
     *
42
     * If a $requestedName is an empty string whole raw value is returned.
43
     * If a $requestedName is a string in dot notation then object will be traversed to find value from those keys.
44
     *
45
     * @param string $requestedName Requested key to be returned
46
     * @param mixed $default Default value to be returned if nothing is found.
47
     * @return mixed
48
     */
49 8
    public function getValue($requestedName = '', $default = null)
50
    {
51 8
        if ($requestedName === '') {
52 1
            return $this->raw;
53
        }
54
55 7
        if (array_key_exists($requestedName, $this->valueCache)) {
56 1
            return $this->valueCache[$requestedName];
57
        }
58
59 7
        if (is_object($this->raw) && property_exists($this->raw, $requestedName)) {
60 2
            return $this->raw->{$requestedName};
61
        }
62
63 5
        $parts = explode('.', $requestedName);
64 5
        $walker = $this->raw;
65
66 5
        $lastPart = array_pop($parts);
67
68 5
        foreach ($parts as $part) {
69 5
            if (is_object($walker) && property_exists($walker, $part)) {
70 5
                $walker = $walker->{$part};
71 5
                continue;
72
            }
73
74 2
            return $this->valueCache[$requestedName] = $default;
75
        }
76
77 3
        if (is_object($walker) && property_exists($walker, $lastPart)) {
78 2
            return $this->valueCache[$requestedName] = $walker->{$lastPart};
79
        }
80
81 1
        return $this->valueCache[$requestedName] = $default;
82
    }
83
}