Completed
Push — master ( 934ce8...14a8a1 )
by Kirill
02:27
created

Setters::__unset()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 20
rs 8.8571
cc 6
eloc 10
nc 9
nop 1
1
<?php
2
/**
3
 * This file is part of Properties package.
4
 *
5
 * @author Serafim <[email protected]>
6
 * @date 14.04.2016 13:11
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 Serafim\Properties;
12
13
use Serafim\Properties\Support\Registry;
14
use Serafim\Properties\Support\Strings as Str;
15
16
/**
17
 * Class Setters
18
 * @package Serafim\Properties
19
 */
20
trait Setters
21
{
22
    /**
23
     * @param string $name
24
     * @param mixed $value
25
     * @return mixed|void
26
     * @throws \InvalidArgumentException
27
     * @throws \LogicException
28
     */
29
    public function __set($name, $value)
30
    {
31
        // Try to call `setProperty` method
32
        $setter = Str::getSetter($name);
33
        if (method_exists($this, $setter)) {
34
            return $this->{$setter}($value);
35
        }
36
37
        $parser = Registry::get($this);
38
        if ($parser->has($name)) {
39
            if ($parser->isWritable($name)) {
40
                $this->setPropertyValue($name, $value);
41
            } else {
42
                $exception = sprintf('Can not set value to read only property %s::$%s', get_class($this), $name);
43
                throw new \LogicException($exception);
44
            }
45
        }
46
47
        $this->$name = $value;
48
    }
49
50
    /**
51
     * @param $name
52
     * @throws \InvalidArgumentException
53
     * @return bool
54
     */
55
    public function __unset($name)
56
    {
57
        $registry = Registry::get($this);
58
59
        $reflection = new \ReflectionClass($this);
60
61
        $isWritableProperty = $registry->has($name) && $registry->isWritable($name) && $reflection->hasProperty($name);
62
63
        if ($isWritableProperty) {
64
            $property = $reflection->getProperty($name);
65
66
            if ($property->isProtected() || $property->isPublic()) {
67
                unset($this->$name);
68
                return true;
69
            }
70
71
        }
72
73
        return false;
74
    }
75
76
    /**
77
     * @param string $name
78
     * @param $value
79
     * @return void
80
     */
81
    private function setPropertyValue($name, $value)
82
    {
83
        $reflection = new \ReflectionProperty($this, $name);
84
        $reflection->setAccessible(true);
85
        $reflection->setValue($this, $value);
86
    }
87
}
88