ArrayUtil::populateArrayFromObject()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.1954
c 0
b 0
f 0
cc 8
nc 6
nop 3
1
<?php
2
3
namespace TomHart\Utilities;
4
5
class ArrayUtil
6
{
7
8
9
    /**
10
     * Given an array of strings, look in the class, or $data for a matching property/key.
11
     * Can also supply nested properties using ->, e.g. parent->name
12
     * @param string[] $params
13
     * @param mixed $model
14
     * @param mixed[] $data
15
     * @return mixed[]
16
     */
17
    public static function populateArrayFromObject(array $params, $model, array $data = [])
18
    {
19
20
        $return = [];
21
        foreach ($params as $name) {
22
            if (isset($data[$name])) {
23
                $return[$name] = $data[$name];
24
                continue;
25
            }
26
            $root = $model;
27
            // Split the name on -> so we can set URL parts from relationships.
28
            $exploded = explode('->', $name);
29
            // Remove the last one, this is the attribute we actually want to get.
30
            $last = array_pop($exploded);
31
            // Change the $root to be whatever relationship in necessary.
32
            foreach ($exploded as $part) {
33
                $root = $root->$part;
34
            }
35
36
            if ($last && (property_exists($root, $last) || (method_exists($root, '__get') && $root->$last))) {
37
                // Get the value.
38
                $return[$name] = $root->$last;
39
                continue;
40
            }
41
42
            $return[$name] = null;
43
        }
44
45
        return $return;
46
    }
47
}
48