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
;
18 * Serialize or deserialize response messages to/from arrays.
20 * This class provides functionality for serializing a ResponseInterface instance
21 * to an array, as well as the reverse operation of creating a Response instance
22 * from an array representing a message.
24 final class ArraySerializer
27 * Serialize a response message to an array.
29 * @param ResponseInterface $response
32 public static function toArray(ResponseInterface
$response)
35 'status_code' => $response->getStatusCode(),
36 'reason_phrase' => $response->getReasonPhrase(),
37 'protocol_version' => $response->getProtocolVersion(),
38 'headers' => $response->getHeaders(),
39 'body' => (string) $response->getBody(),
44 * Deserialize a response array to a response instance.
46 * @param array $serializedResponse
48 * @throws UnexpectedValueException when cannot deserialize response
50 public static function fromArray(array $serializedResponse)
53 $body = new Stream('php://memory', 'wb+');
54 $body->write(self
::getValueFromKey($serializedResponse, 'body'));
56 $statusCode = self
::getValueFromKey($serializedResponse, 'status_code');
57 $headers = self
::getValueFromKey($serializedResponse, 'headers');
58 $protocolVersion = self
::getValueFromKey($serializedResponse, 'protocol_version');
59 $reasonPhrase = self
::getValueFromKey($serializedResponse, 'reason_phrase');
61 return (new Response($body, $statusCode, $headers))
62 ->withProtocolVersion($protocolVersion)
63 ->withStatus($statusCode, $reasonPhrase);
64 } catch (\Exception
$exception) {
65 throw new UnexpectedValueException('Cannot deserialize response', null, $exception);
72 * @param string $message
74 * @throws UnexpectedValueException
76 private static function getValueFromKey(array $data, $key, $message = null)
78 if (isset($data[$key])) {
81 if ($message === null) {
82 $message = sprintf('Missing "%s" key in serialized request', $key);
84 throw new UnexpectedValueException($message);