Completed
Push — master ( 86cfb6...ebc154 )
by Dmitry
03:36
created

Event::index()   C

Complexity

Conditions 8
Paths 21

Size

Total Lines 42
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 0
cts 34
cp 0
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 24
nc 21
nop 2
crap 72
1
<?php
2
3
namespace Basis\Controllers;
4
5
use Basis\Application;
6
use Basis\Event as BasisEvent;
7
use Basis\Service
8
use Exception;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_USE, expecting ',' or ';'
Loading history...
9
10
class Event
11
{
12
    public function index(Application $app, BasisEvent $event, Service $service)
13
    {
14
        try {
15
            if (!array_key_exists('event', $_REQUEST)) {
16
                throw new Exception('No event defined');
17
            }
18
19
            if (!array_key_exists('context', $_REQUEST)) {
20
                throw new Exception('No context defined');
21
            }
22
23
            $context = json_decode($_REQUEST['context']);
24
25
            if (!$context) {
26
                throw new Exception('Invalid context');
27
            }
28
29
            $subscription = $event->getSubscription();
30
31
            if (!array_key_exists($_REQUEST['event'], $subscription)) {
32
                $service->unsubscribe($_REQUEST['event']);
33
                throw new Exception("No subscription on event ".$_REQUEST['event'], 1);
34
            }
35
36
            $result = [];
37
38
            foreach ($subscription[$_REQUEST['event']] as $listener) {
39
                $instance = $app->get('Listeners\\'.$listener);
40
                foreach ($context as $k => $v) {
41
                    $instance->$k = $v;
42
                }
43
                if (!method_exists($instance, 'run')) {
44
                    throw new Exception('No run method for '.$class);
45
                }
46
47
                $result[$listener] = $app->call([$instance, 'run']);
48
            }
49
50
51
            return [
52
                'success' => true,
53
                'data' => $result,
54
            ];
55
        } catch (Exception $e) {
56
            return ['success' => false, 'message' => $e->getMessage()];
57
        }
58
    }
59
}
60