|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Basis\Controller; |
|
4
|
|
|
|
|
5
|
|
|
use Basis\Application; |
|
6
|
|
|
use Basis\Event as BasisEvent; |
|
7
|
|
|
use Basis\Service; |
|
8
|
|
|
use Exception; |
|
9
|
|
|
|
|
10
|
|
|
class Event |
|
11
|
|
|
{ |
|
12
|
|
|
public function index(Application $app, BasisEvent $event, Service $service) |
|
|
|
|
|
|
13
|
|
|
{ |
|
14
|
|
|
try { |
|
15
|
|
|
$context = $this->getRequestContext(); |
|
16
|
|
|
$subscription = $event->getSubscription(); |
|
17
|
|
|
|
|
18
|
|
|
if (!array_key_exists($_REQUEST['event'], $subscription)) { |
|
19
|
|
|
$service->unsubscribe($_REQUEST['event']); |
|
20
|
|
|
throw new Exception("No subscription on event ".$_REQUEST['event'], 1); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
$result = []; |
|
24
|
|
|
|
|
25
|
|
|
foreach ($subscription[$_REQUEST['event']] as $listener) { |
|
26
|
|
|
$instance = $app->get('Listener\\'.$listener); |
|
27
|
|
|
$result[$listener] = $this->handleEvent($instance, $context); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return [ |
|
31
|
|
|
'success' => true, |
|
32
|
|
|
'data' => $result, |
|
33
|
|
|
]; |
|
34
|
|
|
|
|
35
|
|
|
} catch (Exception $e) { |
|
36
|
|
|
return ['success' => false, 'message' => $e->getMessage()]; |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
private function getRequestContext() |
|
|
|
|
|
|
41
|
|
|
{ |
|
42
|
|
|
if (!array_key_exists('event', $_REQUEST)) { |
|
43
|
|
|
throw new Exception('No event defined'); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
if (!array_key_exists('context', $_REQUEST)) { |
|
47
|
|
|
throw new Exception('No context defined'); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$context = json_decode($_REQUEST['context']); |
|
51
|
|
|
|
|
52
|
|
|
if (!$context) { |
|
53
|
|
|
throw new Exception('Invalid context'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $context; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function handleEvent($instance, $context) |
|
60
|
|
|
{ |
|
61
|
|
|
foreach ($context as $k => $v) { |
|
62
|
|
|
$instance->$k = $v; |
|
63
|
|
|
} |
|
64
|
|
|
if (!method_exists($instance, 'run')) { |
|
65
|
|
|
throw new Exception('No run method for '.$class); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $app->call([$instance, 'run']); |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
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: