Completed
Push — master ( a6bfff...553beb )
by Ryosuke
02:24
created

HasSnakeAliases::hasSnakeMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Lampager\Idiorm\Concerns;
4
5
/**
6
 * Trait HasSnakeAliases
7
 */
8
trait HasSnakeAliases
9
{
10
    /**
11
     * @param  string $name
12
     * @return bool
13
     */
14 3
    protected function hasSnakeMethod($name)
15
    {
16 3
        return $this->performOnSnakeMethod(
17 3
            $name,
18 3
            static function () {
19 1
                return true;
20 3
            },
21 3
            static function () {
22 2
                return false;
23 3
            }
24
        );
25
    }
26
27
    /**
28
     * @param  string $name
29
     * @param  array  $args
30
     * @return mixed
31
     */
32 31
    protected function callSnakeMethod($name, array $args)
33
    {
34 31
        return $this->performOnSnakeMethod(
35 31
            $name,
36 31
            function (\ReflectionMethod $method) use ($args) {
37 31
                return $method->invokeArgs($this, $args);
38 31
            },
39 31
            function ($name) {
40 1
                throw new \BadMethodCallException('Call to undefined method ' . static::class . '::' . $name . '()');
41 31
            }
42
        );
43
    }
44
45
    /**
46
     * @param  string   $name
47
     * @param  callable $handleInvoke
48
     * @param  callable $handleError
49
     * @return mixed
50
     */
51 31
    protected function performOnSnakeMethod($name, callable $handleInvoke, callable $handleError)
52
    {
53 31
        static $class;
54 31
        if (!$class) {
55 2
            $class = new \ReflectionClass(static::class);
56
        }
57 31
        $camel = str_replace('_', '', ucwords($name, '_'));
58 31
        if ($class->hasMethod($camel)) {
59 31
            $method = $class->getMethod($camel);
60 31
            if ($method->isPublic()) {
61 31
                return $handleInvoke($method);
62
            }
63
        }
64 2
        return $handleError($name);
65
    }
66
67
    /**
68
     * @param  string $name
69
     * @param  array  $args
70
     * @return mixed
71
     */
72 31
    public function __call($name, array $args)
73
    {
74 31
        return $this->callSnakeMethod($name, $args);
75
    }
76
}
77