Completed
Push — 2.0 ( 359ae1...221cc7 )
by Rafał
51:27 queued 18:07
created

GeoIPSubscriber   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 6
dl 0
loc 46
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSubscribedEvents() 0 8 1
B onKernelRequest() 0 22 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SWP\Bundle\CoreBundle\EventSubscriber;
6
7
use SWP\Bundle\CoreBundle\Enhancer\RouteEnhancer;
8
use SWP\Bundle\CoreBundle\GeoIp\CachedGeoIpChecker;
9
use SWP\Bundle\CoreBundle\Model\ArticleInterface;
10
use SWP\Component\TemplatesSystem\Gimme\Meta\Meta;
11
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
13
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
14
use Symfony\Component\HttpKernel\HttpKernelInterface;
15
use Symfony\Component\HttpKernel\KernelEvents;
16
17
final class GeoIPSubscriber implements EventSubscriberInterface
18
{
19
    /** @var CachedGeoIpChecker */
20
    private $geoIpChecker;
21
22
    /** @var bool */
23
    private $isGeoIpEnabled;
24
25
    public function __construct(CachedGeoIpChecker $geoIpChecker, bool $isGeoIPEnabled = false)
26
    {
27
        $this->geoIpChecker = $geoIpChecker;
28
        $this->isGeoIpEnabled = $isGeoIPEnabled;
29
    }
30
31
    public static function getSubscribedEvents(): array
32
    {
33
        return [
34
            KernelEvents::REQUEST => [
35
                ['onKernelRequest', 1],
36
            ],
37
        ];
38
    }
39
40
    public function onKernelRequest(GetResponseEvent $event): void
41
    {
42
        if (false === $this->isGeoIpEnabled || HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
43
            return;
44
        }
45
46
        $request = $event->getRequest();
47
48
        if (!($content = $request->attributes->get(RouteEnhancer::ARTICLE_META)) instanceof Meta) {
49
            return;
50
        }
51
52
        $object = $content->getValues();
53
54
        if (!$object instanceof ArticleInterface) {
55
            return;
56
        }
57
58
        if (null !== $content && !$this->geoIpChecker->isGranted($request->getClientIp(), $object)) {
59
            throw new AccessDeniedHttpException('Access denied');
60
        }
61
    }
62
}
63