Completed
Push — master ( 1a7ec5...85e2d6 )
by Max
02:41
created

AutoAccessorTrait::getGetterName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace MagicProperties;
4
5
use MagicProperties\Exceptions\InvalidPropertyCallException;
6
7
/**
8
 * Allows access to a getter method implicitly.
9
 */
10
trait AutoAccessorTrait
11
{
12
    /**
13
     * The properties that will be resolved
14
     * via the __get magic method.
15
     *
16
     * @var array
17
     */
18
    protected $gettables = [];
19
20
    /**
21
     * Gets the value of a gettable property.
22
     *
23
     * @param string $property
24
     *
25
     * @throws \MagicProperties\Exceptions\InvalidPropertyCallException
26
     *
27
     * @return void
28
     */
29
    final public function __get($property)
30
    {
31
        if (!property_exists($this, $property)) {
32
            throw new InvalidPropertyCallException(
33
                "You're trying to access to undefined property {$property}.",
34
                InvalidPropertyCallException::UNDEFINED_PROPERTY
35
            );
36
        }
37
38
        $getter = $this->getGetterName($property);
39
40
        if (!in_array($property, $this->gettables) && is_null($getter)) {
41
            throw new InvalidPropertyCallException(
42
                "Property {$property} is not accessible out of the class.",
43
                InvalidPropertyCallException::NOT_ACCESSABLE_PROPERTY
44
            );
45
        }
46
47
        return $this->callGetter($getter, $property);
48
    }
49
50
    /**
51
     * Calls the defined getter for a gettable
52
     * property if there's not defined a getter,
53
     * gets the value directly.
54
     *
55
     * @param string $getter
56
     * @param string $property
57
     *
58
     * @return mixed
59
     */
60
    private function callGetter($getter, $property)
61
    {
62
        if (!is_null($getter)) {
0 ignored issues
show
introduced by
The condition is_null($getter) is always false.
Loading history...
63
            return call_user_func([$this, $getter], $property);
64
        }
65
66
        return $this->$property;
67
    }
68
69
    /**
70
     * Returns the getter name for a
71
     * property or null if there is
72
     * no defined getter method.
73
     *
74
     * @param string $property
75
     *
76
     * @return string|null
77
     */
78
    private function getGetterName($property)
79
    {
80
        if (method_exists($this, toCamelCase($property, 'get'))) {
81
            return toCamelCase($property, 'get');
82
        }
83
84
        if (method_exists($this, toSnakeCase($property, 'get'))) {
85
            return toSnakeCase($property, 'get');
86
        }
87
88
        return null;
89
    }
90
}
91