ClearCache::installDefaultExpressions()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 21
ccs 0
cts 13
cp 0
rs 8.7624
cc 5
eloc 12
nc 8
nop 0
crap 30
1
<?php
2
3
namespace BrainExe\Expression\Listener;
4
5
use BrainExe\Annotations\Annotations\Inject;
6
use BrainExe\Core\Annotations\EventListener;
7
use BrainExe\Core\EventDispatcher\Events\ClearCacheEvent;
8
use BrainExe\Core\Traits\FileCacheTrait;
9
use BrainExe\Core\Traits\LoggerTrait;
10
use BrainExe\Expression\Cache;
11
use BrainExe\Expression\CompilerPass\CacheDefaultExpressions;
12
use BrainExe\Expression\Gateway;
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
15
/**
16
 * @EventListener("Expression.Listener.ClearCache")
17
 */
18
class ClearCache implements EventSubscriberInterface
19
{
20
    use FileCacheTrait;
21
    use LoggerTrait;
22
23
    /**
24
     * @var Gateway
25
     */
26
    private $gateway;
27
28
    /**
29
     * @Inject({"@Expression.Cache", "@Expression.Gateway"})
30
     * @param Cache $cache
31
     * @param Gateway $gateway
32
     */
33
    public function __construct(Cache $cache, Gateway $gateway)
34
    {
35
        $this->cache   = $cache;
0 ignored issues
show
Bug introduced by
The property cache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
        $this->gateway = $gateway;
37
    }
38
39
    public static function getSubscribedEvents()
40
    {
41
        return [
42
            ClearCacheEvent::NAME           => 'rebuildCache',
43
            RebuildExpressionCache::REBUILD => 'rebuildCache'
44
        ];
45
    }
46
47
    public function rebuildCache()
48
    {
49
        $this->cache->writeCache();
50
51
        $this->installDefaultExpressions();
52
    }
53
54
    private function installDefaultExpressions()
55
    {
56
        $existing = [];
57
        foreach ($this->gateway->getAll() as $entity) {
58
            $existing[$entity->expressionId] = true;
59
        };
60
61
        $expressions = $this->includeFile(CacheDefaultExpressions::CACHE_FILE);
62
        if (!$expressions) {
63
            return;
64
        }
65
        foreach ($expressions as $expressionId => $entity) {
66
            if (isset($existing[$expressionId])) {
67
                continue;
68
            }
69
70
            $this->gateway->save($entity);
71
72
            $this->debug(sprintf('Registered entity "%s"', $expressionId));
73
        }
74
    }
75
}
76