3 * @see https://github.com/zendframework/zend-diactoros for the canonical source repository
4 * @copyright Copyright (c) 2015-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;
10 use InvalidArgumentException;
11 use Psr\Http\Message\StreamInterface;
12 use Psr\Http\Message\UriInterface;
15 * Trait with common request behaviors.
17 * Server and client-side requests differ slightly in how the Host header is
18 * handled; on client-side, it should be calculated on-the-fly from the
19 * composed URI (if present), while on server-side, it will be calculated from
20 * the environment. As such, this trait exists to provide the common code
21 * between both client-side and server-side requests, and each can then
22 * use the headers functionality required by their implementations.
34 * The request-target, if it has been provided or calculated.
38 private $requestTarget;
46 * Initialize request state.
48 * Used by constructors.
50 * @param null|string|UriInterface $uri URI for the request, if any.
51 * @param null|string $method HTTP method for the request, if any.
52 * @param string|resource|StreamInterface $body Message body, if any.
53 * @param array $headers Headers for the message, if any.
54 * @throws InvalidArgumentException for any invalid value.
56 private function initialize($uri = null, $method = null, $body = 'php://memory', array $headers = [])
58 $this->validateMethod($method);
60 $this->method = $method ?: '';
61 $this->uri = $this->createUri($uri);
62 $this->stream = $this->getStream($body, 'wb+');
64 $this->setHeaders($headers);
66 // per PSR-7: attempt to set the Host header from a provided URI if no
67 // Host header is provided
68 if (! $this->hasHeader('Host') && $this->uri->getHost()) {
69 $this->headerNames['host'] = 'Host';
70 $this->headers['Host'] = [$this->getHostFromUri()];
75 * Create and return a URI instance.
77 * If `$uri` is a already a `UriInterface` instance, returns it.
79 * If `$uri` is a string, passes it to the `Uri` constructor to return an
82 * If `$uri is null, creates and returns an empty `Uri` instance.
84 * Otherwise, it raises an exception.
86 * @param null|string|UriInterface $uri
87 * @return UriInterface
88 * @throws InvalidArgumentException
90 private function createUri($uri)
92 if ($uri instanceof UriInterface) {
95 if (is_string($uri)) {
101 throw new InvalidArgumentException(
102 'Invalid URI provided; must be null, a string, or a Psr\Http\Message\UriInterface instance'
107 * Retrieves the message's request target.
109 * Retrieves the message's request-target either as it will appear (for
110 * clients), as it appeared at request (for servers), or as it was
111 * specified for the instance (see withRequestTarget()).
113 * In most cases, this will be the origin-form of the composed URI,
114 * unless a value was provided to the concrete implementation (see
115 * withRequestTarget() below).
117 * If no URI is available, and no request-target has been specifically
118 * provided, this method MUST return the string "/".
122 public function getRequestTarget()
124 if (null !== $this->requestTarget) {
125 return $this->requestTarget;
128 $target = $this->uri->getPath();
129 if ($this->uri->getQuery()) {
130 $target .= '?' . $this->uri->getQuery();
133 if (empty($target)) {
141 * Create a new instance with a specific request-target.
143 * If the request needs a non-origin-form request-target — e.g., for
144 * specifying an absolute-form, authority-form, or asterisk-form —
145 * this method may be used to create an instance with the specified
146 * request-target, verbatim.
148 * This method MUST be implemented in such a way as to retain the
149 * immutability of the message, and MUST return a new instance that has the
150 * changed request target.
152 * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various
153 * request-target forms allowed in request messages)
154 * @param mixed $requestTarget
156 * @throws InvalidArgumentException if the request target is invalid.
158 public function withRequestTarget($requestTarget)
160 if (preg_match('#\s#', $requestTarget)) {
161 throw new InvalidArgumentException(
162 'Invalid request target provided; cannot contain whitespace'
167 $new->requestTarget = $requestTarget;
172 * Retrieves the HTTP method of the request.
174 * @return string Returns the request method.
176 public function getMethod()
178 return $this->method;
182 * Return an instance with the provided HTTP method.
184 * While HTTP method names are typically all uppercase characters, HTTP
185 * method names are case-sensitive and thus implementations SHOULD NOT
186 * modify the given string.
188 * This method MUST be implemented in such a way as to retain the
189 * immutability of the message, and MUST return an instance that has the
190 * changed request method.
192 * @param string $method Case-insensitive method.
194 * @throws InvalidArgumentException for invalid HTTP methods.
196 public function withMethod($method)
198 $this->validateMethod($method);
200 $new->method = $method;
205 * Retrieves the URI instance.
207 * This method MUST return a UriInterface instance.
209 * @link http://tools.ietf.org/html/rfc3986#section-4.3
210 * @return UriInterface Returns a UriInterface instance
211 * representing the URI of the request, if any.
213 public function getUri()
219 * Returns an instance with the provided URI.
221 * This method will update the Host header of the returned request by
222 * default if the URI contains a host component. If the URI does not
223 * contain a host component, any pre-existing Host header will be carried
224 * over to the returned request.
226 * You can opt-in to preserving the original state of the Host header by
227 * setting `$preserveHost` to `true`. When `$preserveHost` is set to
228 * `true`, the returned request will not update the Host header of the
229 * returned message -- even if the message contains no Host header. This
230 * means that a call to `getHeader('Host')` on the original request MUST
231 * equal the return value of a call to `getHeader('Host')` on the returned
234 * This method MUST be implemented in such a way as to retain the
235 * immutability of the message, and MUST return an instance that has the
236 * new UriInterface instance.
238 * @link http://tools.ietf.org/html/rfc3986#section-4.3
239 * @param UriInterface $uri New request URI to use.
240 * @param bool $preserveHost Preserve the original state of the Host header.
243 public function withUri(UriInterface $uri, $preserveHost = false)
248 if ($preserveHost && $this->hasHeader('Host')) {
252 if (! $uri->getHost()) {
256 $host = $uri->getHost();
257 if ($uri->getPort()) {
258 $host .= ':' . $uri->getPort();
261 $new->headerNames['host'] = 'Host';
263 // Remove an existing host header if present, regardless of current
264 // de-normalization of the header name.
265 // @see https://github.com/zendframework/zend-diactoros/issues/91
266 foreach (array_keys($new->headers) as $header) {
267 if (strtolower($header) === 'host') {
268 unset($new->headers[$header]);
272 $new->headers['Host'] = [$host];
278 * Validate the HTTP method
280 * @param null|string $method
281 * @throws InvalidArgumentException on invalid HTTP method.
283 private function validateMethod($method)
285 if (null === $method) {
289 if (! is_string($method)) {
290 throw new InvalidArgumentException(sprintf(
291 'Unsupported HTTP method; must be a string, received %s',
292 (is_object($method) ? get_class($method) : gettype($method))
296 if (! preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)) {
297 throw new InvalidArgumentException(sprintf(
298 'Unsupported HTTP method "%s" provided',
305 * Retrieve the host from the URI instance
309 private function getHostFromUri()
311 $host = $this->uri->getHost();
312 $host .= $this->uri->getPort() ? ':' . $this->uri->getPort() : '';