Completed
Push — master ( 1856ca...43d45a )
by Eric
03:58
created

ReflectionAccessor::getPropertyValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Ivory Serializer package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\Serializer\Accessor;
13
14
/**
15
 * @author GeLo <[email protected]>
16
 */
17
class ReflectionAccessor implements AccessorInterface
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function getValue($object, $property)
23
    {
24
        try {
25
            return $this->getPropertyValue($object, $property);
26
        } catch (\ReflectionException $e) {
27
            return $this->getMethodValue($object, $property);
28
        }
29
    }
30
31
    /**
32
     * @param object $object
33
     * @param string $property
34
     *
35
     * @return mixed
36
     */
37
    private function getPropertyValue($object, $property)
38
    {
39
        $reflection = new \ReflectionProperty($object, $property);
40
        $reflection->setAccessible(true);
41
42
        return $reflection->getValue($object);
43
    }
44
45
    /**
46
     * @param object $object
47
     * @param string $property
48
     *
49
     * @return mixed
50
     */
51 View Code Duplication
    private function getMethodValue($object, $property)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
    {
53
        $methods = [];
54
        $suffix = ucfirst($property);
55
56
        foreach (['get', 'has', 'is'] as $prefix) {
57
            try {
58
                $reflection = new \ReflectionMethod($object, $methods[] = $prefix.$suffix);
59
                $reflection->setAccessible(true);
60
61
                return $reflection->invoke($object);
62
            } catch (\ReflectionException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
63
            }
64
        }
65
66
        throw new \InvalidArgumentException(sprintf(
67
            'The property "%s" or methods %s don\'t exist.',
68
            $property,
69
            '"'.implode('", "', $methods).'"'
70
        ));
71
    }
72
}
73