composer package updates
[openemr.git] / vendor / zendframework / zend-diactoros / src / Response / ArraySerializer.php
blob7afe419473ba022c718939cce40e32694aa90f9b
1 <?php
2 /**
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
6 */
8 namespace Zend\Diactoros\Response;
10 use Psr\Http\Message\ResponseInterface;
11 use UnexpectedValueException;
12 use Zend\Diactoros\Response;
13 use Zend\Diactoros\Stream;
15 use function sprintf;
17 /**
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
26 /**
27 * Serialize a response message to an array.
29 * @param ResponseInterface $response
30 * @return array
32 public static function toArray(ResponseInterface $response)
34 return [
35 'status_code' => $response->getStatusCode(),
36 'reason_phrase' => $response->getReasonPhrase(),
37 'protocol_version' => $response->getProtocolVersion(),
38 'headers' => $response->getHeaders(),
39 'body' => (string) $response->getBody(),
43 /**
44 * Deserialize a response array to a response instance.
46 * @param array $serializedResponse
47 * @return Response
48 * @throws UnexpectedValueException when cannot deserialize response
50 public static function fromArray(array $serializedResponse)
52 try {
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);
69 /**
70 * @param array $data
71 * @param string $key
72 * @param string $message
73 * @return mixed
74 * @throws UnexpectedValueException
76 private static function getValueFromKey(array $data, $key, $message = null)
78 if (isset($data[$key])) {
79 return $data[$key];
81 if ($message === null) {
82 $message = sprintf('Missing "%s" key in serialized request', $key);
84 throw new UnexpectedValueException($message);