LicenseListener::onKernelRequest()   C
last analyzed

Complexity

Conditions 12
Paths 13

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 20
c 0
b 0
f 0
nc 13
nop 1
dl 0
loc 40
rs 6.9666

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
declare(strict_types=1);
4
5
namespace AtlassianConnectBundle\Listener;
6
7
use AtlassianConnectBundle\Entity\TenantInterface;
8
use Symfony\Component\HttpFoundation\RedirectResponse;
9
use Symfony\Component\HttpKernel\Event\RequestEvent;
10
use Symfony\Component\Routing\RouterInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
12
13
class LicenseListener
14
{
15
    public function __construct(
16
        private RouterInterface $router,
17
        private TokenStorageInterface $tokenStorage,
18
        private string $environment,
19
        private array $licenseAllowList
20
    ) {
21
    }
22
23
    public function onKernelRequest(RequestEvent $event): void
24
    {
25
        if (!$event->isMainRequest()) {
26
            return;
27
        }
28
29
        $request = $event->getRequest();
30
        $route = $request->attributes->get('_route');
31
32
        if (null !== $route && false === $request->attributes->get('requires_license', false)) {
33
            return;
34
        }
35
36
        if ('active' === $request->query->get('lic') || 'prod' !== $this->environment) {
37
            return;
38
        }
39
40
        // Checking for allowed users
41
        try {
42
            /** @var TenantInterface $user */
43
            $user = $this->tokenStorage->getToken()->getUser();
44
45
            if ($user instanceof TenantInterface && $user->isWhiteListed()) {
46
                return;
47
            }
48
49
            $today = date('Y-m-d');
50
51
            foreach ($this->licenseAllowList as $allowed) {
52
                if ($today <= $allowed['valid_till'] && $allowed['client_key'] === $user->getClientKey()) {
53
                    return;
54
                }
55
            }
56
        } catch (\Throwable $e) {
57
            // Do nothing
58
        }
59
60
        $url = $this->router->generate('atlassian_connect_unlicensed', $request->query->all());
61
        $response = new RedirectResponse($url);
62
        $event->setResponse($response);
63
    }
64
}
65