1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chadicus\Marvel\Api\Cache; |
4
|
|
|
|
5
|
|
|
use Chadicus\Psr\SimpleCache\Serializer\SerializerInterface; |
6
|
|
|
use DominionEnterprises\Util\Arrays; |
7
|
|
|
use GuzzleHttp\Psr7\Response; |
8
|
|
|
use Psr\SimpleCache\InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Provides serialization from arrays to PSR-7 response objects. |
12
|
|
|
*/ |
13
|
|
|
final class Serializer implements SerializerInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Unserializes cached data into the original state. |
17
|
|
|
* |
18
|
|
|
* @param array $data The data to unserialize. |
19
|
|
|
* |
20
|
|
|
* @return Response |
21
|
|
|
*/ |
22
|
|
|
public function unserialize($data) //@codingStandardsIgnoreLine Interface does not define type-hints or return |
23
|
|
|
{ |
24
|
|
|
$this->ensure(is_array($data), '$data was not an array'); |
25
|
|
|
return new Response( |
26
|
|
|
Arrays::get($data, 'statusCode'), |
27
|
|
|
Arrays::get($data, 'headers'), |
28
|
|
|
Arrays::get($data, 'body'), |
29
|
|
|
Arrays::get($data, 'protocolVersion'), |
30
|
|
|
Arrays::get($data, 'reasonPhrase') |
31
|
|
|
); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Serializes the given data for storage in caching. |
36
|
|
|
* |
37
|
|
|
* @param mixed $value The data to serialize for caching. |
38
|
|
|
* |
39
|
|
|
* @return array The result of serializing the given $data. |
40
|
|
|
* |
41
|
|
|
* @throws InvalidArgumentException Thrown if the given value is not a PSR-7 Response instance. |
42
|
|
|
*/ |
43
|
|
|
public function serialize($value) |
44
|
|
|
{ |
45
|
|
|
$this->ensure( |
46
|
|
|
is_a($value, '\\Psr\\Http\\Message\\ResponseInterface'), |
47
|
|
|
'$value was not a PSR-7 Response' |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
return [ |
51
|
|
|
'statusCode' => $value->getStatusCode(), |
52
|
|
|
'headers' => $value->getHeaders(), |
53
|
|
|
'body' => (string)$value->getBody(), |
54
|
|
|
'protocolVersion' => $value->getProtocolVersion(), |
55
|
|
|
'reasonPhrase' => $value->getReasonPhrase(), |
56
|
|
|
]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function ensure(bool $condition, string $message) |
60
|
|
|
{ |
61
|
|
|
if ($condition) { |
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
throw new class($message) extends \Exception implements InvalidArgumentException |
66
|
|
|
{ |
67
|
|
|
}; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|