Passed
Push — master ( 11c56d...7a080f )
by butschster
02:58 queued 18s
created

TopicRegistry::compilePattern()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Broadcasting;
6
7
class TopicRegistry implements TopicRegistryInterface
8
{
9
    private array $patterns = [];
10
11 3
    public function __construct(array $topics = [])
12
    {
13 3
        foreach ($topics as $topic => $callback) {
14 2
            $this->register($topic, $callback);
15
        }
16
    }
17
18 2
    public function register(string $topic, callable $callback): void
19
    {
20 2
        $this->patterns[$this->compilePattern($topic)] = $callback;
21
    }
22
23 2
    public function findCallback(string $topic, array &$matches): ?callable
24
    {
25 2
        foreach ($this->patterns as $pattern => $callback) {
26 2
            if (preg_match($pattern, $topic, $matches)) {
27 2
                return $callback;
28
            }
29
        }
30
31 1
        return null;
32
    }
33
34 2
    private function compilePattern(string $topic): string
35
    {
36 2
        $replaces = [];
37 2
        if (preg_match_all('/\{(\w+):?(.*?)?\}/', $topic, $matches)) {
38 2
            $variables = array_combine($matches[1], $matches[2]);
39 2
            foreach ($variables as $key => $_) {
40 2
                $replaces['{' . $key . '}'] = '(?P<' . $key . '>[^\/\.]+)';
41
            }
42
        }
43
44 2
        return '/^' . strtr($topic, $replaces + ['/' => '\\/', '[' => '(?:', ']' => ')?', '.' => '\.']) . '$/iu';
45
    }
46
}
47