Completed
Push — master ( b1ba92...14d2c0 )
by Iman
03:22 queued 02:15
created

Proxy::sendItThroughPipes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2.032
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 9
    public function __construct($callable, $middlewares)
18
    {
19 9
        $this->callable = $callable;
20 9
        $this->middlewares = $middlewares;
21 9
    }
22
23 9
    public function __call($method, $params)
24
    {
25 9
        $pipeline = new Pipeline(app());
26
27 9
        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 1
                    return call_user_func_array([$this->callable, $method], $params);
41
                } catch (\Throwable $e) {
42
                    return $e;
43
                }
44 3
            };
45
        }
46
47 9
        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 9
    private function sendItThroughPipes($params, Pipeline $pipeline, \Closure $core)
59
    {
60 9
        $result = $pipeline->via('handle')->send($params)->through($this->middlewares)->then($core);
61
62 9
        if ($result instanceof \Throwable) {
63
            throw $result;
64
        } else {
65 9
            return $result;
66
        }
67
    }
68
}
69