PropertyAccessor   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
wmc 13
c 0
b 0
f 0
lcom 0
cbo 0
dl 0
loc 59
ccs 25
cts 30
cp 0.8333
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getByPath() 0 17 7
B setByPath() 0 19 6
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
}