Completed
Push — master ( bbeaa5...179311 )
by Edwin
02:39
created

AbstractBroadcaster::formatChannels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace EdwinLuijten\Ekko\Broadcast\Broadcasters;
4
5
use EdwinLuijten\Ekko\Broadcast\Identity;
6
use EdwinLuijten\Ekko\Broadcast\StrUtil;
7
8
abstract class AbstractBroadcaster
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $channels = [];
14
15
    /**
16
     * @param string $channel
17
     * @param callable $callback
18
     * @return $this
19
     */
20
    public function channel($channel, callable $callback)
21
    {
22
        $this->channels[$channel] = $callback;
23
24
        return $this;
25
    }
26
27
    /**
28
     * @param Identity $identity
29
     * @param string $channel
30
     * @return mixed
31
     * @throws \Exception
32
     */
33
    protected function verifyThatIdentityCanAccessChannel(Identity $identity, $channel)
34
    {
35
        foreach ($this->channels as $key => $callback) {
36
            if (!StrUtil::is($key, $channel)) {
37
                continue;
38
            }
39
40
            $parameters = $this->getAuthenticationParameters($key, $channel);
41
42
            if ($response = $callback($identity, ...$parameters)) {
43
                return $this->validAuthenticationResponse($identity, $response);
44
            }
45
        }
46
47
        throw new \Exception('Unauthorized', 403);
48
    }
49
50
    /**
51
     * @param string $key
52
     * @param string $channel
53
     * @return array
54
     */
55
    protected function getAuthenticationParameters($key, $channel)
56
    {
57
58
        if (!StrUtil::contains($key, '*')) {
59
            return [];
60
        }
61
62
        $pattern = str_replace('\*', '([^\.]+)', preg_quote($key));
63
64
        if (preg_match('/^' . $pattern . '/', $channel, $keys)) {
65
            array_shift($keys);
66
67
            return $keys;
68
        }
69
70
        return [];
71
    }
72
73
    /**
74
     * @param array $channels
75
     * @return array
76
     */
77
    protected function formatChannels(array $channels)
78
    {
79
        return array_map(function ($channel) {
80
            return (string)$channel;
81
        }, $channels);
82
    }
83
}