1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yabacon\Paystack\Helpers; |
4
|
|
|
|
5
|
|
|
use \Closure; |
6
|
|
|
use \Yabacon\Paystack\Contracts\RouteInterface; |
7
|
|
|
use \Yabacon\Paystack\Exception\ValidationException; |
8
|
|
|
|
9
|
|
|
class Router |
10
|
|
|
{ |
11
|
|
|
private $route; |
12
|
|
|
private $route_class; |
13
|
|
|
private $methods; |
14
|
|
|
const ROUTES = ['customer', 'page', 'plan', 'subscription', 'transaction']; |
15
|
|
|
const ROUTE_SINGULAR_LOOKUP = [ |
16
|
|
|
'customers'=>'customer', |
17
|
|
|
'pages'=>'page', |
18
|
|
|
'plans'=>'plan', |
19
|
|
|
'subscriptions'=>'subscription', |
20
|
|
|
'transactions'=>'transaction' |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
const ID_KEY = 'id'; |
24
|
|
|
const PAYSTACK_API_ROOT = 'https://api.paystack.co'; |
25
|
|
|
|
26
|
|
|
public function __call($methd, $sentargs) |
27
|
|
|
{ |
28
|
|
|
$method = ($methd === 'list' ? 'getList' : $methd ); |
29
|
|
|
if (array_key_exists($method, $this->methods) && is_callable($this->methods[$method])) { |
30
|
|
|
return call_user_func_array($this->methods[$method], $sentargs); |
31
|
|
|
} else { |
32
|
|
|
throw new \Exception('Function "' . $method . '" does not exist for "' . $this->route . '".'); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
public static function singularFor($method) |
37
|
|
|
{ |
38
|
|
|
return ( |
39
|
2 |
|
array_key_exists($method, Router::ROUTE_SINGULAR_LOOKUP) ? |
40
|
2 |
|
Router::ROUTE_SINGULAR_LOOKUP[$method] : |
41
|
|
|
null |
42
|
2 |
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
public function __construct($route, $paystackObj) |
46
|
|
|
{ |
47
|
2 |
|
if (!in_array($route, Router::ROUTES)) { |
48
|
2 |
|
throw new ValidationException( |
49
|
2 |
|
"Route '{$route}' does not exist." |
50
|
2 |
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
$this->route = strtolower($route); |
54
|
1 |
|
$this->route_class = 'Yabacon\\Paystack\\Routes\\' . ucwords($route); |
55
|
|
|
|
56
|
1 |
|
$mets = get_class_methods($this->route_class); |
57
|
1 |
|
if (empty($mets)) { |
58
|
|
|
throw new \InvalidArgumentException('Class "' . $this->route . '" does not exist.'); |
59
|
|
|
} |
60
|
|
|
// add methods to this object per method, except root |
61
|
1 |
|
foreach ($mets as $mtd) { |
62
|
1 |
|
if ($mtd === 'root') { |
63
|
1 |
|
continue; |
64
|
|
|
} |
65
|
1 |
|
$mtdFunc = function ( |
66
|
|
|
array $params = [ ], |
67
|
|
|
array $sentargs = [ ] |
68
|
|
|
) use ( |
69
|
|
|
$mtd, |
70
|
|
|
$paystackObj |
71
|
|
|
) { |
72
|
|
|
$interface = call_user_func($this->route_class . '::' . $mtd); |
73
|
|
|
// TODO: validate params and sentargs against definitions |
74
|
|
|
$caller = new Caller($paystackObj); |
75
|
|
|
return $caller->callEndpoint($interface, $params, $sentargs); |
76
|
1 |
|
}; |
77
|
1 |
|
$this->methods[$mtd] = \Closure::bind($mtdFunc, $this, get_class()); |
78
|
1 |
|
} |
79
|
1 |
|
} |
80
|
|
|
} |
81
|
|
|
|