Passed
Pull Request — master (#660)
by butschster
07:38
created

BroadcastConfig::getDriverConfig()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 13
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 27
ccs 0
cts 14
cp 0
crap 30
rs 9.5222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Broadcasting\Config;
6
7
use Spiral\Cache\Exception\InvalidArgumentException;
8
use Spiral\Core\InjectableConfig;
9
10
final class BroadcastConfig extends InjectableConfig
11
{
12
    public const CONFIG = 'broadcasting';
13
14
    protected $config = [
15
        'authorize' => [
16
            'path' => null,
17
            'topics' => [],
18
        ],
19
        'default' => 'null',
20
        'aliases' => [],
21
        'connections' => [],
22
        'driverAliases' => [],
23
    ];
24
    private array $patterns = [];
25
26
    public function __construct(array $config = [])
27
    {
28
        parent::__construct($config);
29
30
        foreach ($config['authorize']['topics'] as $topic => $callback) {
31
            $this->patterns[$this->compilePattern($topic)] = $callback;
32
        }
33
    }
34
35
    /**
36
     * Get authorization path for broadcasting topics.
37
     */
38
    public function getAuthorizationPath(): ?string
39
    {
40
        return $this->config['authorize']['path'] ?? null;
41
    }
42
43
    /**
44
     * Get broadcast driver aliases
45
     */
46
    public function getAliases(): array
47
    {
48
        return (array)($this->config['aliases'] ?? []);
49
    }
50
51
    /**
52
     * Get default broadcast connection
53
     */
54
    public function getDefaultDriver(): string
55
    {
56
        if (!isset($this->config['default']) || empty($this->config['default'])) {
57
            throw new InvalidArgumentException('Default broadcast connection is not defined.');
58
        }
59
60
        if (!\is_string($this->config['default'])) {
61
            throw new InvalidArgumentException('Default broadcast connection config value must be a string');
62
        }
63
64
        return $this->config['default'];
65
    }
66
67
    public function getDriverConfig(string $name): array
68
    {
69
        if (!isset($this->config['connections'][$name])) {
70
            throw new InvalidArgumentException(
71
                sprintf('Config for connection `%s` is not defined.', $name)
72
            );
73
        }
74
75
        $config = $this->config['connections'][$name];
76
77
        if (!isset($config['driver'])) {
78
            throw new InvalidArgumentException(
79
                sprintf('Driver for `%s` connection is not defined.', $name)
80
            );
81
        }
82
83
        if (!\is_string($config['driver'])) {
84
            throw new InvalidArgumentException(
85
                \sprintf('Driver value for `%s` connection must be a string', $name)
86
            );
87
        }
88
89
        if (isset($this->config['driverAliases'][$config['driver']])) {
90
            $config['driver'] = $this->config['driverAliases'][$config['driver']];
91
        }
92
93
        return $config;
94
    }
95
96
    public function findTopicCallback(string $topic, array &$matches): ?callable
97
    {
98
        foreach ($this->patterns as $pattern => $callback) {
99
            if (preg_match($pattern, $topic, $matches)) {
100
                return $callback;
101
            }
102
        }
103
104
        return null;
105
    }
106
107
    private function compilePattern(string $topic): string
108
    {
109
        $replaces = [];
110
        if (preg_match_all('/\{(\w+):?(.*?)?\}/', $topic, $matches)) {
111
            $variables = array_combine($matches[1], $matches[2]);
112
            foreach ($variables as $key => $_) {
113
                $replaces['{' . $key . '}'] = '(?P<' . $key . '>[^\/\.]+)';
114
            }
115
        }
116
117
        return '/^' . strtr($topic, $replaces + ['/' => '\\/', '[' => '(?:', ']' => ')?', '.' => '\.']) . '$/iu';
118
    }
119
}
120