PropertyAccessor::setByPath()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.4689

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
ccs 13
cts 17
cp 0.7647
rs 8.8571
cc 6
eloc 13
nc 6
nop 3
crap 6.4689
1
<?php
2
/**
3
 * For licensing information, please see the LICENSE file accompanied with this file.
4
 *
5
 * @author Gerard van Helden <[email protected]>
6
 * @copyright 2012 Gerard van Helden <http://melp.nl>
7
 */
8
namespace Zicht\Tool\PropertyPath;
9
10
/**
11
 * Utility functions to access an arbitrary property path within a tree-like structure.
12
 */
13
class PropertyAccessor
14
{
15
    /**
16
     * Get a property value by a path of property names or key names.
17
     *
18
     * @param mixed $subject
19
     * @param array $path
20
     * @param bool $notFoundIsError
21
     * @return null
22
     *
23
     * @throws \InvalidArgumentException
24
     */
25 6
    public static function getByPath($subject, array $path, $notFoundIsError = true)
26
    {
27 6
        $ptr = & $subject;
28 6
        foreach ($path as $key) {
29 6
            if (is_object($ptr) && property_exists($ptr, $key)) {
30
                $ptr = & $ptr->$key;
31 6
            } elseif (is_array($ptr) && array_key_exists($key, $ptr)) {
32 5
                $ptr = & $ptr[$key];
33 5
            } else {
34 2
                if ($notFoundIsError === true) {
35 1
                    throw new \OutOfBoundsException("Path not found: " . implode('.', $path) . ", key {$key} did not resolve");
36
                }
37 2
                return null;
38
            }
39 5
        }
40 5
        return $ptr;
41
    }
42
43
44
    /**
45
     * Set a property value by a path of property or key names.
46
     *
47
     * @param mixed &$subject
48
     * @param array $path
49
     * @param mixed $value
50
     * @return mixed
51
     */
52 8
    public static function setByPath(&$subject, array $path, $value)
53
    {
54 8
        $ptr = & $subject;
55 8
        foreach ($path as $key) {
56 8
            if (is_object($ptr)) {
57
                if (!isset($ptr->$key)) {
58
                    $ptr->$key = array();
59
                }
60
                $ptr = & $ptr->$key;
61 8
            } elseif (is_array($ptr)) {
62 8
                if (!isset($ptr[$key])) {
63 8
                    $ptr[$key] = array();
64 8
                }
65 8
                $ptr = & $ptr[$key];
66 8
            }
67 8
        }
68 8
        $ptr = $value;
69 8
        return $subject;
70
    }
71
}