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

CachedGeoIpChecker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Publisher Core Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú.
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\GeoIp;
18
19
use Doctrine\Common\Cache\Cache;
20
use SWP\Bundle\CoreBundle\Model\ArticleInterface;
21
use SWP\Component\GeoIP\Checker\GeoIPChecker;
22
use SWP\Component\GeoIP\Model\GeoIpPlaceInterface;
23
24
class CachedGeoIpChecker
25
{
26
    public const CACHE_KEY_GEO_IP = '_swp_geoip_';
27
28
    /** @var GeoIPChecker */
29
    private $geoIpChecker;
30
31
    /** @var Cache */
32
    private $cacheProvider;
33
34
    public function __construct(GeoIPChecker $geoIPChecker, Cache $cacheProvider)
35
    {
36
        $this->geoIpChecker = $geoIPChecker;
37
        $this->cacheProvider = $cacheProvider;
38
    }
39
40
    public function isGranted(string $ipAddress, ArticleInterface $article): bool
41
    {
42
        if (false === $article instanceof GeoIpPlaceInterface) {
43
            return false;
44
        }
45
46
        $geoIpPlaces = $article->getGeoIpPlaces();
47
48
        $cacheKey = $this->generateCacheKey($ipAddress, $article, $geoIpPlaces);
49
        if (true === $this->cacheProvider->contains($cacheKey)) {
50
            return $this->cacheProvider->fetch($cacheKey);
51
        }
52
53
        $isGranted = $this->geoIpChecker->isGranted($ipAddress, $geoIpPlaces);
54
55
        $this->cacheProvider->save($cacheKey, $isGranted);
56
57
        return $isGranted;
58
    }
59
60
    private function generateCacheKey(string $ipAddress, ArticleInterface $article, array $geoIpPlaces): string
61
    {
62
        return self::CACHE_KEY_GEO_IP.sha1($article->getId().$ipAddress.json_encode($geoIpPlaces, JSON_THROW_ON_ERROR, 512));
63
    }
64
}
65