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;
18 * Serialize or deserialize request messages to/from arrays.
20 * This class provides functionality for serializing a RequestInterface instance
21 * to an array, as well as the reverse operation of creating a Request instance
22 * from an array representing a message.
24 final class ArraySerializer
27 * Serialize a request message to an array.
29 * @param RequestInterface $request
32 public static function toArray(RequestInterface $request)
35 'method' => $request->getMethod(),
36 'request_target' => $request->getRequestTarget(),
37 'uri' => (string) $request->getUri(),
38 'protocol_version' => $request->getProtocolVersion(),
39 'headers' => $request->getHeaders(),
40 'body' => (string) $request->getBody(),
45 * Deserialize a request array to a request instance.
47 * @param array $serializedRequest
49 * @throws UnexpectedValueException when cannot deserialize response
51 public static function fromArray(array $serializedRequest)
54 $uri = self::getValueFromKey($serializedRequest, 'uri');
55 $method = self::getValueFromKey($serializedRequest, 'method');
56 $body = new Stream('php://memory', 'wb+');
57 $body->write(self::getValueFromKey($serializedRequest, 'body'));
58 $headers = self::getValueFromKey($serializedRequest, 'headers');
59 $requestTarget = self::getValueFromKey($serializedRequest, 'request_target');
60 $protocolVersion = self::getValueFromKey($serializedRequest, 'protocol_version');
62 return (new Request($uri, $method, $body, $headers))
63 ->withRequestTarget($requestTarget)
64 ->withProtocolVersion($protocolVersion);
65 } catch (\Exception $exception) {
66 throw new UnexpectedValueException('Cannot deserialize request', null, $exception);
73 * @param string $message
75 * @throws UnexpectedValueException
77 private static function getValueFromKey(array $data, $key, $message = null)
79 if (isset($data[$key])) {
82 if ($message === null) {
83 $message = sprintf('Missing "%s" key in serialized request', $key);
85 throw new UnexpectedValueException($message);