ReflectionReader::isReadable()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 15

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.7666
c 0
b 0
f 0
cc 4
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the rafrsr/lib-array2object package.
5
 *
6
 * (c) Rafael SR <https://github.com/rafrsr>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Rafrsr\LibArray2Object\Reader;
12
13 View Code Duplication
class ReflectionReader implements PropertyReaderInterface
0 ignored issues
show
Duplication introduced by
This class 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...
14
{
15
    protected $onlyPublicProperties;
16
17
    /**
18
     * @param bool $onlyPublicProperties ignore private or protected properties
19
     */
20
    public function __construct($onlyPublicProperties = false)
21
    {
22
        $this->onlyPublicProperties = $onlyPublicProperties;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function isReadable($object, $propertyPath)
29
    {
30
        $classRef = new \ReflectionClass(get_class($object));
31
32
        if (!$classRef->hasProperty($propertyPath)) {
33
            return false;
34
        }
35
36
        $property = $classRef->getProperty($propertyPath);
37
        if ($this->onlyPublicProperties && !$property->isPublic()) {
38
            return false;
39
        }
40
41
        return true;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getValue($object, $propertyPath)
48
    {
49
        if ($this->isReadable($object, $propertyPath)) {
50
            $property = new \ReflectionProperty(get_class($object), $propertyPath);
51
            if (!$property->isPublic()) {
52
                $property->setAccessible(true);
53
            }
54
55
            return $property->getValue($object);
56
        }
57
58
        return;
59
    }
60
}
61