traderinteractive /
tol-api-php
| 1 | <?php |
||
| 2 | |||
| 3 | namespace TraderInteractive\Api; |
||
| 4 | |||
| 5 | use GuzzleHttp\Psr7; |
||
| 6 | use Psr\Http\Message\ResponseInterface; |
||
| 7 | use SubjectivePHP\Psr\SimpleCache\Serializer\SerializerInterface; |
||
| 8 | |||
| 9 | final class ResponseSerializer implements SerializerInterface |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @var array |
||
| 13 | */ |
||
| 14 | const REQUIRED_CACHE_KEYS = [ |
||
| 15 | 'statusCode', |
||
| 16 | 'headers', |
||
| 17 | 'body', |
||
| 18 | ]; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Unserializes cached data into the original psr response. |
||
| 22 | * |
||
| 23 | * @param mixed $data The data to unserialize. |
||
| 24 | * |
||
| 25 | * @return Psr7\Response |
||
| 26 | * |
||
| 27 | * @throws SerializerException Thrown if the given value cannot be unserialized. |
||
| 28 | */ |
||
| 29 | public function unserialize($data) |
||
| 30 | { |
||
| 31 | $this->validateCachedData($data); |
||
| 32 | $statusCode = $data['statusCode']; |
||
| 33 | $headers = $data['headers']; |
||
| 34 | $body = $data['body']; |
||
| 35 | if ($body !== '') { |
||
| 36 | $body = Psr7\Utils::streamFor($body); |
||
| 37 | } |
||
| 38 | |||
| 39 | return new Psr7\Response($statusCode, $headers, $body); |
||
| 40 | } |
||
| 41 | |||
| 42 | /** |
||
| 43 | * Serializes the given psr response for storage in caching. |
||
| 44 | * |
||
| 45 | * @param Psr7\Response $response The http response message to serialize for caching. |
||
| 46 | * |
||
| 47 | * @return mixed The result of serializing the given $data. |
||
| 48 | * |
||
| 49 | * @throws SerializerException Thrown if the given value cannot be serialized for caching. |
||
| 50 | */ |
||
| 51 | public function serialize($response) |
||
| 52 | { |
||
| 53 | if (!($response instanceof ResponseInterface)) { |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 54 | $type = is_object($response) ? get_class($response) : gettype($response); |
||
| 55 | throw new SerializerException("Cannot serialize value of type '{$type}'"); |
||
| 56 | } |
||
| 57 | |||
| 58 | return [ |
||
| 59 | 'statusCode' => $response->getStatusCode(), |
||
| 60 | 'headers' => $response->getHeaders(), |
||
| 61 | 'body' => $response->getBody()->getContents(), |
||
| 62 | ]; |
||
| 63 | } |
||
| 64 | |||
| 65 | private function validateCachedData($data) |
||
| 66 | { |
||
| 67 | if (!is_array($data)) { |
||
| 68 | throw new SerializerException('Serialized data is not an array'); |
||
| 69 | } |
||
| 70 | |||
| 71 | foreach (self::REQUIRED_CACHE_KEYS as $key) { |
||
| 72 | if (!array_key_exists($key, $data)) { |
||
| 73 | throw new SerializerException("Data is missing '{$key}' value"); |
||
| 74 | } |
||
| 75 | } |
||
| 76 | } |
||
| 77 | } |
||
| 78 |