Completed
Branch master (0b0210)
by Patryk
01:47
created

GuzzleClient::setCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace KaLLoSz\Twig\Extension\Client;
4
5
use GuzzleHttp\ClientInterface;
6
use KaLLoSz\Twig\Extension\Cache\CacheInterface;
7
use KaLLoSz\Twig\Extension\IframelyClientInterface;
8
use KaLLoSz\Twig\Extension\IframelyDTO;
9
10
/**
11
 * Class GuzzleClient
12
 * @package KaLLoSz\Twig\Extension\Client
13
 *
14
 * @author Patryk Kala <[email protected]>
15
 */
16
class GuzzleClient implements IframelyClientInterface
17
{
18
    /**
19
     * @var string
20
     */
21
    private $apiKey;
22
23
    /**
24
     * @var ClientInterface
25
     */
26
    private $client;
27
28
    /**
29
     * @var CacheInterface|null
30
     */
31
    private $cache = null;
32
33
    /**
34
     * Class constructor.
35
     *
36
     * @param string|null $apiKey API key.
37
     * @param ClientInterface $client Guzzle Client
38
     */
39 16
    public function __construct(string $apiKey, ClientInterface $client)
40
    {
41 16
        $this->apiKey = $apiKey;
42 16
        $this->client = $client;
43 16
    }
44
45
    /**
46
     * @param CacheInterface $cache
47
     */
48 8
    public function setCache(CacheInterface $cache)
49
    {
50 8
        $this->cache = $cache;
51 8
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 12
    public function getUrlData(string $url): IframelyDTO
57
    {
58 12
        if ($this->cache && $this->cache->has(CacheInterface::KEY_PREFIX.md5($url))) {
59 4
            return $this->cache->get(CacheInterface::KEY_PREFIX.md5($url));
60
        }
61
62 8
        $response = $this->client->request(
63 8
            'GET',
64 8
            IframelyClientInterface::API_BASE_URI,
65 8
            ['query' => ['api_key' => $this->apiKey, 'url' => $url, 'html' => 1]]
66
        );
67
68 8
        $dto = new IframelyDTO(json_decode($response->getBody()->getContents(), true));
69
70 8
        if ($this->cache) {
71 4
            $this->cache->save(CacheInterface::KEY_PREFIX.md5($url), $dto, CacheInterface::LIFETIME_DAY);
72
        }
73
74 8
        return $dto;
75
    }
76
}
77