Listener::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4286
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
namespace BrainExe\Expression;
4
5
use BrainExe\Annotations\Annotations\Inject;
6
use BrainExe\Annotations\Annotations\Service;
7
use BrainExe\Core\Traits\FileCacheTrait;
8
use Generator;
9
use Symfony\Component\EventDispatcher\Event;
10
use Symfony\Component\EventDispatcher\EventDispatcher;
11
12
/**
13
 * @Service("Expression.Listener", public=false)
14
 */
15
class Listener extends EventDispatcher
16
{
17
18
    use FileCacheTrait;
19
20
    /**
21
     * @var Gateway
22
     */
23
    private $gateway;
24
25
    /**
26
     * @var Language
27
     */
28
    private $language;
29
30
    /**
31
     * @Inject({"@Expression.Gateway", "@Expression.Language"})
32
     * @param Gateway $gateway
33
     * @param Language $language
34
     */
35
    public function __construct(Gateway $gateway, Language $language)
36
    {
37
        $this->gateway  = $gateway;
38
        $this->language = $language;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function dispatch($eventName, Event $event = null)
45
    {
46
        $cachedFunction = $this->includeFile(Cache::CACHE_FILE);
47
        if (!$cachedFunction) {
48
            return;
49
        }
50
51
        /** @var Generator|Entity[] $matches */
52
        $matches = call_user_func($cachedFunction, $event, $eventName, $this);
53
        foreach ($matches as $entity) {
54
            $parameters = [
55
                'event'     => $event,
56
                'eventName' => $eventName,
57
                'entity'    => $entity
58
            ];
59
60
            $oldParams = $entity->payload;
61
            foreach ($entity->actions as $action) {
62
                $this->language->evaluate($action, $parameters);
63
            }
64
65
            if ($entity->payload != $oldParams) {
66
                $this->gateway->save($entity);
67
            }
68
        }
69
    }
70
}
71