Completed
Push — master ( fef923...c0df34 )
by Rafael
03:03
created

ReflectionWriter::isWritable()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 9.2
cc 4
eloc 8
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\Writer;
11
12
/**
13
 * Class ReflectionWriter
14
 */
15
class ReflectionWriter implements PropertyWriterInterface
16
{
17
18
    protected $onlyPublicProperties;
19
20
    /**
21
     * @param boolean $onlyPublicProperties ignore private or protected properties
22
     */
23
    public function __construct($onlyPublicProperties = false)
24
    {
25
        $this->onlyPublicProperties = $onlyPublicProperties;
26
    }
27
28
    /**
29
     * @inheritDoc
30
     */
31
    public function isWritable($object, $propertyPath)
32
    {
33
        $classRef = new \ReflectionClass(get_class($object));
34
35
        if (!$classRef->hasProperty($propertyPath)) {
36
            return false;
37
        }
38
39
        $property = $classRef->getProperty($propertyPath);
40
        if ($this->onlyPublicProperties && !$property->isPublic()) {
41
            return false;
42
        }
43
44
        return true;
45
    }
46
47
    /**
48
     * @inheritDoc
49
     */
50
    public function setValue(&$object, $propertyPath, $value)
51
    {
52
        if ($this->isWritable($object, $propertyPath)) {
53
            $property = new \ReflectionProperty(get_class($object), $propertyPath);
54
            if (!$property->isPublic()) {
55
                $property->setAccessible(true);
56
            }
57
58
            $property->setValue($object, $value);
59
        }
60
    }
61
}