Passed
Pull Request — master (#20)
by Igor
02:11
created

ObjectFunctions::getPropertyValue()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7.0283

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 11
nc 6
nop 2
dl 0
loc 23
ccs 11
cts 12
cp 0.9167
crap 7.0283
rs 8.8333
c 2
b 0
f 0
1
<?php
2
/**
3
 * @author Maxim Sokolovsky
4
 */
5
6
namespace WS\Utils\Collections\Functions;
7
8
use ReflectionProperty;
9
use RuntimeException;
10
11
class ObjectFunctions
12
{
13
    /**
14
     * @param $object
15
     * @param string $fieldName
16
     * @return mixed
17
     * @noinspection PhpDocMissingThrowsInspection
18
     */
19 50
    public static function getPropertyValue($object, string $fieldName)
20
    {
21 50
        if (is_array($object)) {
22 21
            return $object[$fieldName] ?? null;
23
        }
24
25
        /** @noinspection PhpUnhandledExceptionInspection */
26 30
        if (property_exists($object, $fieldName) && (new ReflectionProperty($object, $fieldName))->isPublic()) {
27 12
            return $object->{$fieldName};
28
        }
29
30 21
        if (isset($object->{$fieldName})) {
31
            return $object->{$fieldName};
32
        }
33
34 21
        if (method_exists($object, $fieldName)) {
35 5
            return $object->{$fieldName}();
36
        }
37
38 18
        if (method_exists($object, 'get'.$fieldName)) {
39 17
            return $object->{'get'.$fieldName}();
40
        }
41 2
        throw new RuntimeException("Field $fieldName is not exist for object ".var_export($object, true));
42
    }
43
}
44