Completed
Push — master ( 4b4c57...035a27 )
by Rafael
03:03
created

ReflectionReader::getValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 13
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 13
loc 13
rs 9.4285
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
3
/**
4
 * LICENSE: This file is subject to the terms and conditions defined in
5
 * file 'LICENSE', which is part of this source code package.
6
 *
7
 * @copyright 2016 Copyright(c) - All rights reserved.
8
 */
9
10
namespace Rafrsr\LibArray2Object\Reader;
11
12 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...
13
{
14
    protected $onlyPublicProperties;
15
16
    /**
17
     * @param boolean $onlyPublicProperties ignore private or protected properties
18
     */
19
    public function __construct($onlyPublicProperties = false)
20
    {
21
        $this->onlyPublicProperties = $onlyPublicProperties;
22
    }
23
24
    /**
25
     * @inheritDoc
26
     */
27
    public function isReadable($object, $propertyPath)
28
    {
29
        $classRef = new \ReflectionClass(get_class($object));
30
31
        if (!$classRef->hasProperty($propertyPath)) {
32
            return false;
33
        }
34
35
        $property = $classRef->getProperty($propertyPath);
36
        if ($this->onlyPublicProperties && !$property->isPublic()) {
37
            return false;
38
        }
39
40
        return true;
41
    }
42
43
    /**
44
     * @inheritDoc
45
     */
46
    public function getValue($object, $propertyPath)
47
    {
48
        if ($this->isReadable($object, $propertyPath)) {
49
            $property = new \ReflectionProperty(get_class($object), $propertyPath);
50
            if (!$property->isPublic()) {
51
                $property->setAccessible(true);
52
            }
53
54
            return $property->getValue($object);
55
        }
56
57
        return null;
58
    }
59
}