|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Basis\Controllers; |
|
4
|
|
|
|
|
5
|
|
|
use Basis\Filesystem; |
|
6
|
|
|
use Basis\Runner; |
|
7
|
|
|
use Exception; |
|
8
|
|
|
|
|
9
|
|
|
class Api |
|
10
|
|
|
{ |
|
11
|
|
|
public function index(Runner $runner) |
|
|
|
|
|
|
12
|
|
|
{ |
|
13
|
|
|
if(!array_key_exists('rpc', $_REQUEST)) { |
|
14
|
|
|
return [ |
|
15
|
|
|
'success' => false, |
|
16
|
|
|
'message' => 'No rpc defined', |
|
17
|
|
|
]; |
|
18
|
|
|
} |
|
19
|
|
|
$data = json_decode($_REQUEST['rpc']); |
|
20
|
|
|
|
|
21
|
|
|
if(!$data) { |
|
22
|
|
|
return [ |
|
23
|
|
|
'success' => false, |
|
24
|
|
|
'message' => 'Invalid rpc format', |
|
25
|
|
|
]; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
$request = is_array($data) ? $data : [$data]; |
|
29
|
|
|
|
|
30
|
|
|
$response = []; |
|
31
|
|
|
foreach($request as $rpc) { |
|
32
|
|
|
$result = $this->process($runner, $rpc); |
|
33
|
|
|
if(property_exists($rpc, 'tid')) { |
|
34
|
|
|
$result['tid'] = $rpc->tid; |
|
35
|
|
|
} |
|
36
|
|
|
$response[] = $result; |
|
37
|
|
|
} |
|
38
|
|
|
return is_array($data) ? $response : $response[0]; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
private function process($runner, $rpc) |
|
42
|
|
|
{ |
|
43
|
|
|
if(!property_exists($rpc, 'job')) { |
|
44
|
|
|
return [ |
|
45
|
|
|
'success' => false, |
|
46
|
|
|
'message' => 'Invalid rpc format: no job', |
|
47
|
|
|
]; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
if(!property_exists($rpc, 'params')) { |
|
51
|
|
|
return [ |
|
52
|
|
|
'success' => false, |
|
53
|
|
|
'message' => 'Invalid rpc format: no params', |
|
54
|
|
|
]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
try { |
|
58
|
|
|
$params = is_object($rpc->params) ? get_object_vars($rpc->params) : []; |
|
59
|
|
|
return [ |
|
60
|
|
|
'success' => true, |
|
61
|
|
|
'data' => $runner->dispatch($rpc->job, $params), |
|
62
|
|
|
]; |
|
63
|
|
|
|
|
64
|
|
|
} catch(Exception $e) { |
|
65
|
|
|
return [ |
|
66
|
|
|
'success' => false, |
|
67
|
|
|
'message' => $e->getMessage(), |
|
68
|
|
|
'trace' => explode(PHP_EOL, $e->getTraceAsString()), |
|
69
|
|
|
]; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: