Completed
Push — master ( efd7c9...b0bd3b )
by Iman
01:34
created

Proxy   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 64
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __call() 0 26 4
A sendItThroughPipes() 0 10 2
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 11
    public function __construct($callable, $middlewares)
18
    {
19 11
        $this->callable = $callable;
20 11
        $this->middlewares = $middlewares;
21 11
    }
22
23 11
    public function __call($method, $params)
24
    {
25 11
        $pipeline = new Pipeline(app());
26
27 11
        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 5
            };
45
        }
46
47 11
        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 11
    private function sendItThroughPipes($params, Pipeline $pipeline, \Closure $core)
59
    {
60 11
        $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