Completed
Push — master ( 145a7f...613e75 )
by Ibrahim
02:02
created

Router::__call()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.2
ccs 0
cts 0
cp 0
cc 4
eloc 6
nc 4
nop 2
crap 20
1
<?php
2
3
namespace Yabacon\Paystack\Helpers;
4
5
use \Closure;
6
use \Yabacon\Paystack\Contracts\RouteInterface;
7
8
class Router
9
{
10
    private $route;
11
    private $route_class;
12
    private $methods;
13
14
    const ID_KEY = 'id';
15
    const PAYSTACK_API_ROOT = 'https://api.paystack.co';
16
17
    public function __call($methd, $sentargs)
18
    {
19
        $method = ($methd === 'list' ? 'getList' : $methd );
20
        if (array_key_exists($method, $this->methods) && is_callable($this->methods[$method])) {
21
            return call_user_func_array($this->methods[$method], $sentargs);
22
        } else {
23
            // User attempted to call a function that does not exist
24
            throw new \Exception('Function "' . $method . '" does not exist for "' . $this->route . '".');
25
        }
26
    }
27
28
    public function __construct($route, $paystackObj)
29
    {
30
        $this->route = strtolower($route);
31
        $this->route_class = 'Yabacon\\Paystack\\Routes\\' . ucwords($route);
32
33
        $mets = get_class_methods($this->route_class);
34
        if (empty($mets)) {
35
            throw new \InvalidArgumentException('Class "' . $this->route . '" does not exist.');
36
        }
37
        // add methods to this object per method, except root
38
        foreach ($mets as $mtd) {
39
            if ($mtd === 'root') {
40
                // skip root method
41
                continue;
42
            }
43
            $mtdFunc = function (
44
                array $params = [ ],
45
                array $sentargs = [ ]
46
            ) use (
47
                $mtd,
48
                $paystackObj
49
) {
50
                $interface = call_user_func($this->route_class . '::' . $mtd);
51
                // TODO: validate params and sentargs against definitions
52
                $caller = new Caller($paystackObj);
53
                return $caller->callEndpoint($interface, $params, $sentargs);
54
            };
55
            $this->methods[$mtd] = \Closure::bind($mtdFunc, $this, get_class());
56
        }
57
    }
58
}
59