Passed
Push — master ( a22e59...74f1f1 )
by Ryosuke
17:33 queued 15:53
created

HasSnakeAliases::callSnakeMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

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