AutoMutatorTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A callSetter() 0 11 3
A __set() 0 17 3
1
<?php
2
3
namespace MagicProperties;
4
5
use MagicProperties\Exceptions\InvalidPropertyCallException;
6
7
/**
8
 * Allows access to a setter implicitly.
9
 */
10
trait AutoMutatorTrait
11
{
12
    /**
13
     * The properties that will be resolved
14
     * via the __set magic method.
15
     *
16
     * @var array
17
     */
18
    protected $settables = [];
19
20
    /**
21
     * Sets the value of a settable property.
22
     *
23
     * @param string $property
24
     * @param mixed  $value
25
     *
26
     * @throws MagicProperties\Exceptions\InvalidPropertyCallException
27
     *
28
     * @return void
29
     */
30
    final public function __set($property, $value)
31
    {
32
        if (!property_exists($this, $property)) {
33
            throw new InvalidPropertyCallException(
34
                "You're trying to access to undefined property {$property}.",
35
                InvalidPropertyCallException::UNDEFINED_PROPERTY
36
            );
37
        }
38
39
        if (!in_array($property, $this->settables)) {
40
            throw new InvalidPropertyCallException(
41
                "Property {$property} is not accessible out of the class.",
42
                InvalidPropertyCallException::NOT_ACCESSABLE_PROPERTY
43
            );
44
        }
45
46
        $this->callSetter($property, $value);
47
    }
48
49
    /**
50
     * Calls the defined setter for a settable
51
     * property if there's not defined a setter,
52
     * sets the value directly.
53
     *
54
     * @param string $property
55
     * @param mixed  $value
56
     *
57
     * @return void
58
     */
59
    private function callSetter($property, $value)
60
    {
61
        if (method_exists($this, toCamelCase($property, 'set'))) {
62
            call_user_func_array([$this, toCamelCase($property, 'set')], [$value]);
63
        }
64
65
        if (method_exists($this, toSnakeCase($property, 'set'))) {
66
            call_user_func_array([$this, toSnakeCase($property, 'set')], [$value]);
67
        }
68
69
        $this->$property = $value;
70
    }
71
}
72