Passed
Push — main ( 95bf12...ddea62 )
by Leo
02:29
created

RestProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 6
rs 10
1
<?php
2
3
namespace MetroMarkets\FFBundle\Providers;
4
5
use GuzzleHttp\Client;
6
use MetroMarkets\FFBundle\Contract\ProviderInterface;
7
use Symfony\Component\Cache\Adapter\AdapterInterface;
8
9
class RestProvider implements ProviderInterface
10
{
11
    /** @var Client */
12
    private $client;
13
14
    /** @var string */
15
    private $endpoint;
16
17
    /** @var AdapterInterface */
18
    private $cache;
19
20
    /** @var int */
21
    private $cacheTTL;
22
23
    public function __construct(string $endpoint, AdapterInterface $cache = null, int $cacheTTL = 60)
24
    {
25
        $this->client = new Client();
26
        $this->endpoint = $endpoint;
27
        $this->cache = $cache;
28
        $this->cacheTTL = $cacheTTL;
29
    }
30
31
    public function isEnabled(string $key, string $identifier = null): bool
32
    {
33
        if (!$this->cache) {
34
            return $this->fetchData($key);
35
        }
36
37
        return $this->getCachedResponse($key);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getCachedResponse($key) could return the type null which is incompatible with the type-hinted return boolean. Consider adding an additional type-check to rule them out.
Loading history...
38
    }
39
40
    private function getCachedResponse(string $key)
41
    {
42
        $cacheItem = $this->cache->getItem($key);
43
44
        if ($cacheItem->isHit()) {
45
            return $cacheItem->get();
46
        }
47
48
        $result = $this->fetchData($key);
49
50
        $cacheItem->set($result);
51
        $cacheItem->expiresAfter($this->cacheTTL);
52
        $this->cache->save($cacheItem);
53
54
    }
55
56
    private function fetchData(string $key)
57
    {
58
        $response = $this->client->get($this->endpoint . '?key=' . $key);
59
60
        return \json_decode($response->getBody()->getContents(), true);
61
    }
62
}