1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Basis\Controller; |
4
|
|
|
|
5
|
|
|
use Basis\Config; |
6
|
|
|
use Basis\Event; |
|
|
|
|
7
|
|
|
use Basis\Filesystem; |
8
|
|
|
use Basis\Runner; |
9
|
|
|
use Exception; |
10
|
|
|
|
11
|
|
|
class Api |
12
|
|
|
{ |
13
|
|
|
public function index(Config $config, Runner $runner, Event $event) |
|
|
|
|
14
|
|
|
{ |
15
|
|
|
if (!array_key_exists('rpc', $_REQUEST)) { |
16
|
|
|
return [ |
17
|
|
|
'success' => false, |
18
|
|
|
'message' => 'No rpc defined', |
19
|
|
|
]; |
20
|
|
|
} |
21
|
|
|
$data = json_decode($_REQUEST['rpc']); |
22
|
|
|
|
23
|
|
|
if (!$data) { |
24
|
|
|
return [ |
25
|
|
|
'success' => false, |
26
|
|
|
'message' => 'Invalid rpc format', |
27
|
|
|
]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$request = is_array($data) ? $data : [$data]; |
31
|
|
|
|
32
|
|
|
$response = []; |
33
|
|
|
foreach ($request as $rpc) { |
34
|
|
|
$result = $this->process($runner, $rpc); |
35
|
|
|
if (property_exists($rpc, 'tid')) { |
36
|
|
|
$result['tid'] = $rpc->tid; |
37
|
|
|
} |
38
|
|
|
$response[] = $result; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
try { |
42
|
|
|
$event->fireChanges(); |
43
|
|
|
} catch (Exception $e) { |
44
|
|
|
return ['success' => false, 'message' => $e->getMessage()]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return is_array($data) ? $response : $response[0]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function process($runner, $rpc) |
51
|
|
|
{ |
52
|
|
|
if (!property_exists($rpc, 'job')) { |
53
|
|
|
return [ |
54
|
|
|
'success' => false, |
55
|
|
|
'message' => 'Invalid rpc format: no job', |
56
|
|
|
]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if (!property_exists($rpc, 'params')) { |
60
|
|
|
return [ |
61
|
|
|
'success' => false, |
62
|
|
|
'message' => 'Invalid rpc format: no params', |
63
|
|
|
]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
try { |
67
|
|
|
$params = is_object($rpc->params) ? get_object_vars($rpc->params) : []; |
68
|
|
|
return [ |
69
|
|
|
'success' => true, |
70
|
|
|
'data' => $runner->dispatch($rpc->job, $params), |
71
|
|
|
]; |
72
|
|
|
} catch (Exception $e) { |
73
|
|
|
return [ |
74
|
|
|
'success' => false, |
75
|
|
|
'message' => $e->getMessage(), |
76
|
|
|
'trace' => explode(PHP_EOL, $e->getTraceAsString()), |
77
|
|
|
]; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: