Proxy::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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