Completed
Push — master ( 14d2c0...efd7c9 )
by Iman
01:55
created

Proxy::__call()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 12
cts 12
cp 1
rs 9.504
c 0
b 0
f 0
cc 4
nc 2
nop 2
crap 4
1
<?php
2
3
namespace Imanghafoori\Middlewarize;
4
5
class Proxy
6
{
7
    private $callable;
8
9
    private $middlewares;
10
11
    /**
12
     * Proxy constructor.
13
     *
14
     * @param $callable
15
     * @param $middlewares
16
     */
17 10
    public function __construct($callable, $middlewares)
18
    {
19 10
        $this->callable = $callable;
20 10
        $this->middlewares = $middlewares;
21 10
    }
22
23 10
    public function __call($method, $params)
24
    {
25 10
        $pipeline = new Pipeline(app());
26
27 10
        if (!is_string($this->callable)) {
28
            // for method calls on objects.
29
            $core = (function ($params) use ($method) {
30
                try {
31 4
                    return $this->$method(...$params);
32 1
                } catch (\Throwable $e) {
33 1
                    return $e;
34
                }
35 6
            })->bindTo($this->callable, $this->callable);
36
        } else {
37
            // for static method calls on classes.
38
            $core = function ($params) use ($method) {
39
                try {
40 2
                    return call_user_func_array([$this->callable, $method], $params);
41 1
                } catch (\Throwable $e) {
42 1
                    return $e;
43
                }
44 4
            };
45
        }
46
47 10
        return $this->sendItThroughPipes($params, $pipeline, $core);
48
    }
49
50
    /**
51
     * @param $params
52
     * @param Pipeline $pipeline
53
     * @param \Closure $core
54
     *
55
     * @throws \Throwable
56
     * @return mixed
57
     */
58 10
    private function sendItThroughPipes($params, Pipeline $pipeline, \Closure $core)
59
    {
60 10
        $result = $pipeline->via('handle')->send($params)->through($this->middlewares)->then($core);
61
62 10
        if ($result instanceof \Throwable) {
63
            throw $result;
64
        } else {
65 10
            return $result;
66
        }
67
    }
68
}
69