Completed
Push — master ( 601de6...446929 )
by Dmitry
04:40
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 Exception;
7
use Basis\Event as BasisEvent;
8
9
class Event
10
{
11
    public function index(Application $app, BasisEvent $event)
0 ignored issues
show
Coding Style introduced by
index uses the super-global variable $_REQUEST which is generally not recommended.

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:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
12
    {
13
        try {
14
            if (!array_key_exists('event', $_REQUEST)) {
15
                throw new Exception('No event defined');
16
            }
17
18
            if (!array_key_exists('context', $_REQUEST)) {
19
                throw new Exception('No context defined');
20
            }
21
22
            $context = json_decode($_REQUEST['context']);
23
24
            if (!$context) {
25
                throw new Exception('Invalid context');
26
            }
27
28
            $class = 'Listeners';
29
            foreach (explode('.', $_REQUEST['event']) as $part) {
30
                $class .= '\\'.ucfirst($part);
31
            }
32
33
            $instance = $app->get($class);
34
            foreach ($context as $k => $v) {
35
                $instance->$k = $v;
36
            }
37
            if (!method_exists($instance, 'run')) {
38
                throw new Exception('No run method for '.$class);
39
            }
40
41
            $result = $app->call([$instance, 'run']);
42
43
            $event->fireChanges();
44
45
            return [
46
                'success' => true,
47
                'data' => $result,
48
            ];
49
        } catch (Exception $e) {
50
            return ['success' => false, 'message' => $e->getMessage()];
51
        }
52
    }
53
}
54