Completed
Pull Request — master (#24)
by
unknown
02:50
created

AbstractCoreApiClient::generateCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 3
1
<?php
2
3
namespace MovingImage\Client\VMPro\ApiClient;
4
5
use GuzzleHttp\ClientInterface;
6
use JMS\Serializer\Serializer;
7
use MovingImage\Client\VMPro\Exception;
8
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
9
use Psr\Cache\CacheItemPoolInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Log\LoggerAwareInterface;
12
use Symfony\Component\Cache\Adapter\NullAdapter;
13
14
/**
15
 * Class AbstractCoreApiClient.
16
 *
17
 * @author Ruben Knol <[email protected]>
18
 */
19
abstract class AbstractCoreApiClient implements LoggerAwareInterface
20
{
21
    use LoggerAwareTrait;
22
23
    /**
24
     * @const string
25
     */
26
    const OPT_VIDEO_MANAGER_ID = 'videoManagerId';
27
28
    /**
29
     * @var ClientInterface The Guzzle HTTP client
30
     */
31
    protected $httpClient;
32
33
    /**
34
     * @var Serializer The JMS Serializer instance
35
     */
36
    protected $serializer;
37
38
    /**
39
     * @var CacheItemPoolInterface PSR6 cache pool implementation
40
     */
41
    protected $cacheItemPool;
42
43
    /**
44
     * @var mixed time-to-live for cached responses
45
     *            The type of this property might be integer, \DateInterval or null
46
     *
47
     * @see CacheItemInterface::expiresAfter()
48
     */
49
    protected $cacheTtl;
50
51
    /**
52
     * ApiClient constructor.
53
     *
54
     * @param ClientInterface        $httpClient
55
     * @param Serializer             $serializer
56
     * @param CacheItemPoolInterface $cacheItemPool
57
     * @param int                    $cacheTtl
58
     */
59
    public function __construct(
60
        ClientInterface $httpClient,
61
        Serializer $serializer,
62
        CacheItemPoolInterface $cacheItemPool = null,
63
        $cacheTtl = null
64
    ) {
65
        $this->httpClient = $httpClient;
66
        $this->serializer = $serializer;
67
        $this->cacheItemPool = $cacheItemPool ?: new NullAdapter();
68
        $this->cacheTtl = $cacheTtl;
69
    }
70
71
    /**
72
     * Perform the actual request in the implementation classes.
73
     *
74
     * @param string $method
75
     * @param string $uri
76
     * @param array  $options
77
     *
78
     * @return mixed
79
     */
80
    abstract protected function _doRequest($method, $uri, $options);
81
82
    /**
83
     * Make a request to the API and serialize the result according to our
84
     * serialization strategy.
85
     *
86
     * @param string $method
87
     * @param string $uri
88
     * @param array  $options
89
     *
90
     * @return object|ResponseInterface
91
     */
92
    protected function makeRequest($method, $uri, $options)
93
    {
94
        $logger = $this->getLogger();
95
96
        try {
97
            // Automagically pre-pend videoManagerId if the option is present in the
98
            // options for sending the request
99
            if (isset($options[self::OPT_VIDEO_MANAGER_ID])) {
100
                $uri = sprintf('%d/%s', $options[self::OPT_VIDEO_MANAGER_ID], $uri);
101
            }
102
103
            $cacheKey = $this->generateCacheKey($method, $uri, $options);
104
            $cacheItem = $this->cacheItemPool->getItem($cacheKey);
105
            if ($cacheItem->isHit()) {
106
                $logger->info(sprintf('Getting response from cache for %s request to %s', $method, $uri), [$uri]);
107
108
                return $this->unserializeResponse($cacheItem->get());
109
            }
110
111
            $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$uri]);
112
113
            /** @var ResponseInterface $response */
114
            $response = $this->_doRequest($method, $uri, $options);
115
116
            $cacheItem->set($this->serializeResponse($response));
117
            $cacheItem->expiresAfter($this->cacheTtl);
118
            $this->cacheItemPool->save($cacheItem);
119
120
            $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]);
121
            $logger->debug('Response JSON was:', [$response->getBody()]);
122
123
            return $response;
124
        } catch (\Exception $e) {
125
            throw $e; // Just rethrow for now
126
        }
127
    }
128
129
    /**
130
     * Deserialize a response into an instance of it's associated class.
131
     *
132
     * @param string $data
133
     * @param string $serialisationClass
134
     *
135
     * @return object
136
     */
137
    protected function deserialize($data, $serialisationClass)
138
    {
139
        return $this->serializer->deserialize($data, $serialisationClass, 'json');
140
    }
141
142
    /**
143
     * Helper method to build the JSON data array for making a request
144
     * with ::makeRequest(). Optional parameters with empty or null value will be
145
     * omitted from the return value.
146
     *
147
     * Examples:
148
     *
149
     * $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test'])
150
     *
151
     * Would result in:
152
     *
153
     * [
154
     *     'title' => 'test',
155
     *     'bla' => 'test',
156
     * ]
157
     *
158
     * @param array $required
159
     * @param array $optional
160
     *
161
     * @return array
162
     */
163
    protected function buildJsonParameters(array $required, array $optional)
164
    {
165
        foreach ($required as $key => $value) {
166
            if (empty($value)) {
167
                throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key));
168
            }
169
        }
170
171
        $json = $required;
172
173
        foreach ($optional as $key => $value) {
174
            if (!empty($value) || $value === false) {
175
                $json[$key] = $value;
176
            }
177
        }
178
179
        return $json;
180
    }
181
182
    /**
183
     * Generates the cache key based on request method, uri and options.
184
     *
185
     * @param string $method
186
     * @param string $uri
187
     * @param array  $options
188
     *
189
     * @return string
190
     */
191
    private function generateCacheKey($method, $uri, array $options = [])
192
    {
193
        return sha1(sprintf('%s.%s.%s', $method, $uri, json_encode($options)));
194
    }
195
196
    /**
197
     * Serializes the provided response to a string, suitable for caching.
198
     * The type of the $response argument varies depending on the guzzle version.
199
     *
200
     * @param mixed $response
201
     *
202
     * @return string
203
     */
204
    abstract protected function serializeResponse($response);
205
206
    /**
207
     * Unserializes the serialized response into a response object.
208
     * The return type varies depending on the guzzle version.
209
     *
210
     * @param string $serialized
211
     *
212
     * @return mixed
213
     *
214
     * @throws Exception
215
     */
216
    abstract protected function unserializeResponse($serialized);
217
}
218