ArrayUtil   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 0
dl 0
loc 43
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B populateArrayFromObject() 0 30 8
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