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\Request;
10 use Psr\Http\Message\RequestInterface;
11 use UnexpectedValueException;
12 use Zend\Diactoros\Request;
13 use Zend\Diactoros\Stream;
16 * Serialize or deserialize request messages to/from arrays.
18 * This class provides functionality for serializing a RequestInterface instance
19 * to an array, as well as the reverse operation of creating a Request instance
20 * from an array representing a message.
22 final class ArraySerializer
25 * Serialize a request message to an array.
27 * @param RequestInterface $request
30 public static function toArray(RequestInterface $request)
33 'method' => $request->getMethod(),
34 'request_target' => $request->getRequestTarget(),
35 'uri' => (string) $request->getUri(),
36 'protocol_version' => $request->getProtocolVersion(),
37 'headers' => $request->getHeaders(),
38 'body' => (string) $request->getBody(),
43 * Deserialize a request array to a request instance.
45 * @param array $serializedRequest
47 * @throws UnexpectedValueException when cannot deserialize response
49 public static function fromArray(array $serializedRequest)
52 $uri = self::getValueFromKey($serializedRequest, 'uri');
53 $method = self::getValueFromKey($serializedRequest, 'method');
54 $body = new Stream('php://memory', 'wb+');
55 $body->write(self::getValueFromKey($serializedRequest, 'body'));
56 $headers = self::getValueFromKey($serializedRequest, 'headers');
57 $requestTarget = self::getValueFromKey($serializedRequest, 'request_target');
58 $protocolVersion = self::getValueFromKey($serializedRequest, 'protocol_version');
60 return (new Request($uri, $method, $body, $headers))
61 ->withRequestTarget($requestTarget)
62 ->withProtocolVersion($protocolVersion);
63 } catch (\Exception $exception) {
64 throw new UnexpectedValueException('Cannot deserialize request', null, $exception);
71 * @param string $message
73 * @throws UnexpectedValueException
75 private static function getValueFromKey(array $data, $key, $message = null)
77 if (isset($data[$key])) {
80 if ($message === null) {
81 $message = sprintf('Missing "%s" key in serialized request', $key);
83 throw new UnexpectedValueException($message);