Passed
Pull Request — master (#225)
by Anton
02:23
created

WebsocketsConfig   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 22
c 1
b 0
f 0
dl 0
loc 73
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getServerCallback() 0 3 1
A compilePattern() 0 11 3
A findTopicCallback() 0 9 3
A getPath() 0 3 1
A __construct() 0 6 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Broadcast\Config;
13
14
use Spiral\Core\InjectableConfig;
15
16
final class WebsocketsConfig extends InjectableConfig
17
{
18
    public const CONFIG = 'websockets';
19
20
    /** @var array */
21
    protected $config = [
22
        'path'            => '',
23
        'authorizeServer' => null,
24
        'authorizeTopics' => []
25
    ];
26
27
    /** @var array */
28
    private $patterns = [];
29
30
    /**
31
     * @param array $config
32
     */
33
    public function __construct(array $config = [])
34
    {
35
        parent::__construct($config);
36
37
        foreach ($config['authorizeTopics'] as $topic => $callback) {
38
            $this->patterns[$this->compilePattern($topic)] = $callback;
39
        }
40
    }
41
42
    /**
43
     * @return string|null
44
     */
45
    public function getPath(): string
46
    {
47
        return $this->config['path'];
48
    }
49
50
    /**
51
     * @return callable|null
52
     */
53
    public function getServerCallback(): ?callable
54
    {
55
        return $this->config['authorizeServer'];
56
    }
57
58
    /**
59
     * @param string $topic
60
     * @param array  $matches
61
     * @return callable|null
62
     */
63
    public function findTopicCallback(string $topic, array &$matches): ?callable
64
    {
65
        foreach ($this->patterns as $pattern => $callback) {
66
            if (preg_match($pattern, $topic, $matches)) {
67
                return $callback;
68
            }
69
        }
70
71
        return null;
72
    }
73
74
    /**
75
     * @param string $topic
76
     * @return string
77
     */
78
    private function compilePattern(string $topic): string
79
    {
80
        $replaces = [];
81
        if (preg_match_all('/\{(\w+):?(.*?)?\}/', $topic, $matches)) {
82
            $variables = array_combine($matches[1], $matches[2]);
83
            foreach ($variables as $key => $segment) {
84
                $replaces['{' . $key . '}'] = '(?P<' . $key . '>[^\/\.]+)';
85
            }
86
        }
87
88
        return '/^' . strtr($topic, $replaces + ['/' => '\\/', '[' => '(?:', ']' => ')?', '.' => '\.']) . '$/iu';
89
    }
90
}
91