Client::saveToCache()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Zoho\Subscription\Client;
5
6
use Doctrine\Common\Cache\Cache;
7
use Http\Discovery\HttpClientDiscovery;
8
use Http\Discovery\MessageFactoryDiscovery;
9
use Psr\Http\Message\ResponseInterface;
10
11
class Client
12
{
13
    protected $token;
14
15
    protected $organizationId;
16
17
    protected $cache;
18
19
    protected $client;
20
21
    protected $ttl;
22
23
    protected $messageFactory;
24
25
    public function __construct(string $token, int $organizationId, Cache $cache, int $ttl = 7200)
26
    {
27
        $this->token = $token;
28
        $this->organizationId = $organizationId;
29
        $this->ttl = $ttl;
30
        $this->cache = $cache;
31
        $this->client = HttpClientDiscovery::find();
32
        $this->messageFactory = MessageFactoryDiscovery::find();
33
    }
34
35
    public function getFromCache(string $key)
36
    {
37
        // If the results are already cached
38
        if ($this->cache->contains($key)) {
39
            return unserialize($this->cache->fetch($key));
40
        }
41
42
        return false;
43
    }
44
45
    public function saveToCache(string $key, $values): bool
46
    {
47
        return $this->cache->save($key, serialize($values), $this->ttl);
48
    }
49
50
    public function deleteCacheByKey(string $key)
51
    {
52
        $this->cache->delete($key);
53
    }
54
55
    protected function processResponse(ResponseInterface $response): array
56
    {
57
        $data = json_decode($response->getBody()->getContents(), true);
58
59
        if ($data['code'] != 0) {
60
            throw new \Exception('Zoho Api subscription error : '.$data['message']);
61
        }
62
63
        return $data;
64
    }
65
66
    protected function sendRequest(string $method, string $uri, array $headers = [], string $body = null)
67
    {
68
        $baseUri = 'https://subscriptions.zoho.com/api/v1/';
69
        $request = $this->messageFactory->createRequest($method, $baseUri.$uri, $this->getRequestHeaders($headers), $body);
70
71
        return $this->client->sendRequest($request);
72
    }
73
74
    protected function getRequestHeaders(array $headers = [])
75
    {
76
        $defaultHeaders = [
77
            'Authorization' => 'Zoho-authtoken '.$this->token,
78
            'X-com-zoho-subscriptions-organizationid' => $this->organizationId,
79
        ];
80
81
        return array_merge($defaultHeaders, $headers);
82
    }
83
}
84