Completed
Pull Request — master (#2)
by Artem
01:17
created

PrivateChannelAuthenticator::processRequest()   B

Complexity

Conditions 10
Paths 7

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 7.6666
c 0
b 0
f 0
cc 10
nc 7
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of the FreshCentrifugoBundle.
4
 *
5
 * (c) Artem Henvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fresh\CentrifugoBundle\Service\ChannelAuthenticator;
14
15
use Fresh\CentrifugoBundle\Service\Credentials\CredentialsGenerator;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
19
/**
20
 * PrivateChannelAuthenticator.
21
 *
22
 * @author Artem Henvald <[email protected]>
23
 */
24
class PrivateChannelAuthenticator
25
{
26
    /** @var CredentialsGenerator */
27
    private $credentialsGenerator;
28
29
    /** @var ChannelAuthenticatorInterface[]|iterable */
30
    private $channelAuthenticators;
31
32
    /**
33
     * @param CredentialsGenerator                     $credentialsGenerator
34
     * @param ChannelAuthenticatorInterface[]|iterable $channelAuthenticators
35
     */
36
    public function __construct(CredentialsGenerator $credentialsGenerator, iterable $channelAuthenticators)
37
    {
38
        $this->credentialsGenerator = $credentialsGenerator;
39
        $this->channelAuthenticators = $channelAuthenticators;
40
    }
41
42
    /**
43
     * @param Request $request
44
     *
45
     * @return array
46
     */
47
    public function authChannelsForClientFromRequest(Request $request): array
48
    {
49
        $authData = [];
50
51
        [$client, $channels] = $this->processRequest($request);
0 ignored issues
show
Bug introduced by
The variable $client does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $channels does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
52
53
        foreach ($channels as $channel) {
54
            $token = $this->authChannelForClient($client, (string) $channel);
55
56
            if (\is_string($token)) {
57
                $authData[] = [
58
                    'channel' => (string) $channel,
59
                    'token' => $token,
60
                ];
61
            }
62
        }
63
64
        return ['channels' => $authData];
65
    }
66
67
    /**
68
     * @param string $client
69
     * @param string $channel
70
     *
71
     * @return string|null
72
     */
73
    private function authChannelForClient(string $client, string $channel): ?string
74
    {
75
        $token = null;
76
77
        $channelAuthenticator = $this->findAppropriateChannelAuthenticator($channel);
78
        if ($channelAuthenticator instanceof ChannelAuthenticatorInterface && $channelAuthenticator->hasAccessToChannel($channel)) {
79
            $token = $this->credentialsGenerator->generateJwtTokenForPrivateChannel($client, $channel);
80
        }
81
82
        return $token;
83
    }
84
85
    /**
86
     * @param string $channel
87
     *
88
     * @return ChannelAuthenticatorInterface|null
89
     */
90
    private function findAppropriateChannelAuthenticator(string $channel): ?ChannelAuthenticatorInterface
91
    {
92
        foreach ($this->channelAuthenticators as $channelAuthenticator) {
93
            if ($channelAuthenticator->supports($channel)) {
94
                return $channelAuthenticator;
95
            }
96
        }
97
98
        return null;
99
    }
100
101
    /**
102
     * @param Request $request
103
     *
104
     * @throws BadRequestHttpException
105
     * @throws \Exception
106
     *
107
     * @return array
108
     */
109
    private function processRequest(Request $request): array
110
    {
111
        try {
112
            $content = \json_decode((string) $request->getContent(), true, 512, \JSON_THROW_ON_ERROR);
113
        } catch (\JsonException $e) {
114
            throw new BadRequestHttpException('Invalid JSON.');
115
        } catch (\Exception $e) {
116
            throw $e;
117
        }
118
119
        if (!isset($content['client']) || !\is_string($content['client'])) {
120
            throw new BadRequestHttpException('Client must be set in request.');
121
        }
122
        $result[] = $content['client'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
123
124
        if (!isset($content['channels']) || !\is_array($content['channels']) || empty($content['channels'])) {
125
            throw new BadRequestHttpException('Channels must be set in request.');
126
        }
127
128
        foreach ($content['channels'] as $channel) {
129
            if (!\is_string($channel)) {
130
                throw new BadRequestHttpException('Channel must be a string.');
131
            }
132
        }
133
134
        $result[] = $content['channels'];
135
136
        return $result;
137
    }
138
}
139