3 * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
4 * @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
5 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
8 namespace Zend\Diactoros\Response;
10 use Psr\Http\Message\ResponseInterface;
11 use UnexpectedValueException;
12 use Zend\Diactoros\Response;
13 use Zend\Diactoros\Stream;
16 * Serialize or deserialize response messages to/from arrays.
18 * This class provides functionality for serializing a ResponseInterface instance
19 * to an array, as well as the reverse operation of creating a Response instance
20 * from an array representing a message.
22 final class ArraySerializer
25 * Serialize a response message to an array.
27 * @param ResponseInterface $response
30 public static function toArray(ResponseInterface $response)
33 'status_code' => $response->getStatusCode(),
34 'reason_phrase' => $response->getReasonPhrase(),
35 'protocol_version' => $response->getProtocolVersion(),
36 'headers' => $response->getHeaders(),
37 'body' => (string) $response->getBody(),
42 * Deserialize a response array to a response instance.
44 * @param array $serializedResponse
46 * @throws UnexpectedValueException when cannot deserialize response
48 public static function fromArray(array $serializedResponse)
51 $body = new Stream('php://memory', 'wb+');
52 $body->write(self::getValueFromKey($serializedResponse, 'body'));
54 $statusCode = self::getValueFromKey($serializedResponse, 'status_code');
55 $headers = self::getValueFromKey($serializedResponse, 'headers');
56 $protocolVersion = self::getValueFromKey($serializedResponse, 'protocol_version');
57 $reasonPhrase = self::getValueFromKey($serializedResponse, 'reason_phrase');
59 return (new Response($body, $statusCode, $headers))
60 ->withProtocolVersion($protocolVersion)
61 ->withStatus($statusCode, $reasonPhrase);
62 } catch (\Exception $exception) {
63 throw new UnexpectedValueException('Cannot deserialize response', null, $exception);
70 * @param string $message
72 * @throws UnexpectedValueException
74 private static function getValueFromKey(array $data, $key, $message = null)
76 if (isset($data[$key])) {
79 if ($message === null) {
80 $message = sprintf('Missing "%s" key in serialized request', $key);
82 throw new UnexpectedValueException($message);