Completed
Push — master ( 4848aa...64d9da )
by Dmitry
03:44
created

Service::subscribe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Basis;
4
5
use Exception;
6
use Tarantool\Mapper\Pool;
7
8
class Service
9
{
10
    private $app;
11
    private $name;
12
13
    public function __construct($name, Application $app)
14
    {
15
        $this->app = $app;
16
        $this->name = $name;
17
    }
18
19 6
    public function getName() : string
20
    {
21 6
        return $this->name;
22
    }
23
24
    private $services;
25
26 1
    public function listServices() : array
27
    {
28 1
        return $this->services ?: $this->services = $this->app->dispatch('web.services')->services;
29
    }
30
31 2
    public function subscribe(string $event)
32
    {
33 2
        $this->app->dispatch('event.subscribe', [
34 2
            'event' => $event,
35 2
            'service' => $this->getName(),
36
        ]);
37 2
    }
38
39
    public function unsubscribe(string $event)
40
    {
41
        $this->app->dispatch('event.unsubscribe', [
42
            'event' => $event,
43
            'service' => $this->getName(),
44
        ]);
45
    }
46
47
    private $eventExistence = [];
48
49 1
    public function eventExists(string $event) : bool
50
    {
51 1
        if (array_key_exists($event, $this->eventExistence)) {
52
            return $this->eventExistence[$event];
53
        }
54 1
        $types = $this->app->get(Pool::class)->get('event')->find('type');
55
56 1
        foreach ($types as $type) {
57 1
            if ($this->eventMatch($event, $type->nick)) {
58 1
                return $this->eventExistence[$event] = true;
59
            }
60
        }
61
62 1
        return $this->eventExistence[$event] = false;
63
    }
64
65 1
    public function eventMatch($event, $spec)
66
    {
67 1
        if ($spec == $event) {
68 1
            return true;
69 1
        } else if (strpos($spec, '*') !== false) {
70 1
            $spec = explode('.', $spec);
71 1
            $event = explode('.', $event);
72 1
            $valid = true;
73 1
            foreach (range(0, 2) as $part) {
74 1
                $valid = $valid && ($spec[$part] == '*' || $spec[$part] == $event[$part]);
75
            }
76 1
            return $valid;
77
        }
78 1
        return false;
79
    }
80
}
81