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

GuzzleClient   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 61
c 0
b 0
f 0
wmc 6
lcom 1
cbo 4
ccs 18
cts 18
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setCache() 0 4 1
A getUrlData() 0 20 4
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