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
|
|
|
$patterns = []; |
19
|
|
|
foreach (array_keys($subscription) as $pattern) { |
20
|
|
|
if ($service->eventMatch($context->event, $pattern)) { |
21
|
|
|
$patterns[] = $pattern; |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
if (!count($patterns)) { |
26
|
|
|
$service->unsubscribe($context->event); |
27
|
|
|
throw new Exception("No subscription on event ".$_REQUEST['event'], 1); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$listeners = []; |
31
|
|
|
foreach ($patterns as $pattern) { |
32
|
|
|
foreach ($subscription[$pattern] as $listener) { |
33
|
|
|
if (!array_key_exists($listener, $listeners)) { |
34
|
|
|
$listeners[$listener] = $app->get('Listener\\'.$listener); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$result = []; |
40
|
|
|
foreach ($listeners as $nick => $listener) { |
41
|
|
|
$result[$nick] = $this->handleEvent($app, $listener, $context); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return [ |
45
|
|
|
'success' => true, |
46
|
|
|
'data' => $result, |
47
|
|
|
]; |
48
|
|
|
|
49
|
|
|
} catch (Exception $e) { |
50
|
|
|
return ['success' => false, 'message' => $e->getMessage()]; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function getRequestContext() |
|
|
|
|
55
|
|
|
{ |
56
|
|
|
if (!array_key_exists('event', $_REQUEST)) { |
57
|
|
|
throw new Exception('No event defined'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
if (!array_key_exists('context', $_REQUEST)) { |
61
|
|
|
throw new Exception('No context defined'); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$context = json_decode($_REQUEST['context']); |
65
|
|
|
|
66
|
|
|
if (!$context) { |
67
|
|
|
throw new Exception('Invalid context'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$context->event = $_REQUEST['event']; |
71
|
|
|
|
72
|
|
|
return $context; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function handleEvent($app, $instance, $context) |
76
|
|
|
{ |
77
|
|
|
foreach ($context as $k => $v) { |
78
|
|
|
$instance->$k = $v; |
79
|
|
|
} |
80
|
|
|
if (!method_exists($instance, 'run')) { |
81
|
|
|
throw new Exception('No run method for '.$class); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $app->call([$instance, 'run']); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
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: