Completed
Push — master ( f2e227...0d4270 )
by Ruben
02:34
created

AbstractCoreApiClient::deserialize()   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 2
1
<?php
2
3
namespace MovingImage\Client\VMPro\ApiClient;
4
5
use Cache\Adapter\Void\VoidCachePool;
6
use GuzzleHttp\ClientInterface;
7
use JMS\Serializer\Serializer;
8
use MovingImage\Client\VMPro\Exception;
9
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
10
use Psr\Cache\CacheItemPoolInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Log\LoggerAwareInterface;
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 VoidCachePool();
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
            if ($this->isCachable($method, $uri, $options, $response)) {
117
                $cacheItem->set($this->serializeResponse($response));
118
                $cacheItem->expiresAfter($this->cacheTtl);
119
                $this->cacheItemPool->save($cacheItem);
120
            }
121
122
            $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]);
123
            $logger->debug('Response JSON was:', [$response->getBody()]);
124
125
            return $response;
126
        } catch (\Exception $e) {
127
            throw $e; // Just rethrow for now
128
        }
129
    }
130
131
    /**
132
     * Deserialize a response into an instance of it's associated class.
133
     *
134
     * @param string $data
135
     * @param string $serialisationClass
136
     *
137
     * @return object
138
     */
139
    protected function deserialize($data, $serialisationClass)
140
    {
141
        return $this->serializer->deserialize($data, $serialisationClass, 'json');
142
    }
143
144
    /**
145
     * Helper method to build the JSON data array for making a request
146
     * with ::makeRequest(). Optional parameters with empty or null value will be
147
     * omitted from the return value.
148
     *
149
     * Examples:
150
     *
151
     * $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test'])
152
     *
153
     * Would result in:
154
     *
155
     * [
156
     *     'title' => 'test',
157
     *     'bla' => 'test',
158
     * ]
159
     *
160
     * @param array $required
161
     * @param array $optional
162
     *
163
     * @return array
164
     */
165
    protected function buildJsonParameters(array $required, array $optional)
166
    {
167
        foreach ($required as $key => $value) {
168
            if (empty($value)) {
169
                throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key));
170
            }
171
        }
172
173
        $json = $required;
174
175
        foreach ($optional as $key => $value) {
176
            if (!empty($value) || $value === false) {
177
                $json[$key] = $value;
178
            }
179
        }
180
181
        return $json;
182
    }
183
184
    /**
185
     * Generates the cache key based on the class name, request method, uri and options.
186
     *
187
     * @param string $method
188
     * @param string $uri
189
     * @param array  $options
190
     *
191
     * @return string
192
     */
193
    private function generateCacheKey($method, $uri, array $options = [])
194
    {
195
        return sha1(sprintf('%s.%s.%s.%s', get_class($this), $method, $uri, json_encode($options)));
196
    }
197
198
    /**
199
     * Checks if the request may be cached.
200
     *
201
     * @param string $method
202
     * @param string $uri
203
     * @param array  $options
204
     * @param mixed  $response
205
     *
206
     * @return bool
207
     */
208
    private function isCachable($method, $uri, array $options, $response)
0 ignored issues
show
Unused Code introduced by
The parameter $uri is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
209
    {
210
        /** @var ResponseInterface $statusCode */
211
        $statusCode = $response->getStatusCode();
212
213
        return $method === 'GET' && $statusCode >= 200 && $statusCode < 300;
214
    }
215
216
    /**
217
     * Serializes the provided response to a string, suitable for caching.
218
     * The type of the $response argument varies depending on the guzzle version.
219
     *
220
     * @param mixed $response
221
     *
222
     * @return string
223
     */
224
    abstract protected function serializeResponse($response);
225
226
    /**
227
     * Unserializes the serialized response into a response object.
228
     * The return type varies depending on the guzzle version.
229
     *
230
     * @param string $serialized
231
     *
232
     * @return mixed
233
     *
234
     * @throws Exception
235
     */
236
    abstract protected function unserializeResponse($serialized);
237
}
238