Completed
Push — master ( 3dab4c...0f5459 )
by Max
01:20
created

GetterHelper::get()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.0555
c 0
b 0
f 0
nc 11
cc 9
nop 4
1
<?php
2
3
/*
4
 *  @copyright (c) 2019 Mendel <[email protected]>
5
 *  @license see license.txt
6
 */
7
8
namespace drycart\data;
9
10
/**
11
 * Wrapper for pretty access to field
12
 * Used for deep access to some data at some unknown data
13
 *
14
 * fieldName for example forum.moderators.first().name work correct for any of this sence:
15
 * $data->forum->moderators->first()->name
16
 * $data['forum']['moderators']->first()['name']
17
 * $data['forum']->moderators->first()['name']
18
 * etc...
19
 *
20
 * Object field is priority option, second is array, after this we try method,
21
 * so if exist something like this, it will be used
22
 * $data['forum']->moderators['first()']['name']
23
 *
24
 * methods parameters not supports at any format
25
 */
26
class GetterHelper
27
{
28
    /**
29
     * Get some data by pretty name
30
     * 
31
     * @param array|object $data data for pretty access
32
     * @param string $name name for access
33
     * @param bool $safe if true - Exception for not exist fields
34
     * @param mixed $default used for non safe request, if we dont find answer
35
     * @return mixed
36
     * @throws \Exception
37
     */
38
    public static function get($data, string $name, bool $safe = true, $default = null) {
39
        $fields = explode('.', $name);
40
        foreach ($fields as $key) {
41
            if (is_array($data)) { // Just array, because ArrayAccess can have his own logic as object field
42
                $data = (object) $data;
43
            }
44
            //
45
            if (isset($data->{$key})) { // simple
46
                $data = $data->{$key};
47
            } elseif (is_a($data, \ArrayAccess::class) and isset($data[$key])) { // for ArrayAccess obj
48
                $data = $data[$key];
49
                // Methods magic...
50
            } elseif ((substr($key, -2) == '()') and method_exists($data, substr($key, 0, -2))) {
51
                $data = call_user_func_array([$data, substr($key, 0, -2)], []);
52
            } elseif ($safe) {
53
                throw new \Exception("Bad field name $key at name $name fields");
54
            } else {
55
                return $default;
56
            }
57
        }
58
        return $data;
59
    }
60
}
61