5f506207e92cbcde23f39f1d46fe942dd2586534
[yaffs-website] / src / MessageTrait.php
1 <?php
2 /**
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
6  */
7
8 namespace Zend\Diactoros;
9
10 use InvalidArgumentException;
11 use Psr\Http\Message\StreamInterface;
12
13 /**
14  * Trait implementing the various methods defined in MessageInterface.
15  *
16  * @see https://github.com/php-fig/http-message/tree/master/src/MessageInterface.php
17  */
18 trait MessageTrait
19 {
20     /**
21      * List of all registered headers, as key => array of values.
22      *
23      * @var array
24      */
25     protected $headers = [];
26
27     /**
28      * Map of normalized header name to original name used to register header.
29      *
30      * @var array
31      */
32     protected $headerNames = [];
33
34     /**
35      * @var string
36      */
37     private $protocol = '1.1';
38
39     /**
40      * @var StreamInterface
41      */
42     private $stream;
43
44     /**
45      * Retrieves the HTTP protocol version as a string.
46      *
47      * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
48      *
49      * @return string HTTP protocol version.
50      */
51     public function getProtocolVersion()
52     {
53         return $this->protocol;
54     }
55
56     /**
57      * Return an instance with the specified HTTP protocol version.
58      *
59      * The version string MUST contain only the HTTP version number (e.g.,
60      * "1.1", "1.0").
61      *
62      * This method MUST be implemented in such a way as to retain the
63      * immutability of the message, and MUST return an instance that has the
64      * new protocol version.
65      *
66      * @param string $version HTTP protocol version
67      * @return static
68      */
69     public function withProtocolVersion($version)
70     {
71         $this->validateProtocolVersion($version);
72         $new = clone $this;
73         $new->protocol = $version;
74         return $new;
75     }
76
77     /**
78      * Retrieves all message headers.
79      *
80      * The keys represent the header name as it will be sent over the wire, and
81      * each value is an array of strings associated with the header.
82      *
83      *     // Represent the headers as a string
84      *     foreach ($message->getHeaders() as $name => $values) {
85      *         echo $name . ": " . implode(", ", $values);
86      *     }
87      *
88      *     // Emit headers iteratively:
89      *     foreach ($message->getHeaders() as $name => $values) {
90      *         foreach ($values as $value) {
91      *             header(sprintf('%s: %s', $name, $value), false);
92      *         }
93      *     }
94      *
95      * @return array Returns an associative array of the message's headers. Each
96      *     key MUST be a header name, and each value MUST be an array of strings.
97      */
98     public function getHeaders()
99     {
100         return $this->headers;
101     }
102
103     /**
104      * Checks if a header exists by the given case-insensitive name.
105      *
106      * @param string $header Case-insensitive header name.
107      * @return bool Returns true if any header names match the given header
108      *     name using a case-insensitive string comparison. Returns false if
109      *     no matching header name is found in the message.
110      */
111     public function hasHeader($header)
112     {
113         return isset($this->headerNames[strtolower($header)]);
114     }
115
116     /**
117      * Retrieves a message header value by the given case-insensitive name.
118      *
119      * This method returns an array of all the header values of the given
120      * case-insensitive header name.
121      *
122      * If the header does not appear in the message, this method MUST return an
123      * empty array.
124      *
125      * @param string $header Case-insensitive header field name.
126      * @return string[] An array of string values as provided for the given
127      *    header. If the header does not appear in the message, this method MUST
128      *    return an empty array.
129      */
130     public function getHeader($header)
131     {
132         if (! $this->hasHeader($header)) {
133             return [];
134         }
135
136         $header = $this->headerNames[strtolower($header)];
137
138         return $this->headers[$header];
139     }
140
141     /**
142      * Retrieves a comma-separated string of the values for a single header.
143      *
144      * This method returns all of the header values of the given
145      * case-insensitive header name as a string concatenated together using
146      * a comma.
147      *
148      * NOTE: Not all header values may be appropriately represented using
149      * comma concatenation. For such headers, use getHeader() instead
150      * and supply your own delimiter when concatenating.
151      *
152      * If the header does not appear in the message, this method MUST return
153      * an empty string.
154      *
155      * @param string $name Case-insensitive header field name.
156      * @return string A string of values as provided for the given header
157      *    concatenated together using a comma. If the header does not appear in
158      *    the message, this method MUST return an empty string.
159      */
160     public function getHeaderLine($name)
161     {
162         $value = $this->getHeader($name);
163         if (empty($value)) {
164             return '';
165         }
166
167         return implode(',', $value);
168     }
169
170     /**
171      * Return an instance with the provided header, replacing any existing
172      * values of any headers with the same case-insensitive name.
173      *
174      * While header names are case-insensitive, the casing of the header will
175      * be preserved by this function, and returned from getHeaders().
176      *
177      * This method MUST be implemented in such a way as to retain the
178      * immutability of the message, and MUST return an instance that has the
179      * new and/or updated header and value.
180      *
181      * @param string $header Case-insensitive header field name.
182      * @param string|string[] $value Header value(s).
183      * @return static
184      * @throws \InvalidArgumentException for invalid header names or values.
185      */
186     public function withHeader($header, $value)
187     {
188         $this->assertHeader($header);
189
190         $normalized = strtolower($header);
191
192         $new = clone $this;
193         if ($new->hasHeader($header)) {
194             unset($new->headers[$new->headerNames[$normalized]]);
195         }
196
197         $value = $this->filterHeaderValue($value);
198
199         $new->headerNames[$normalized] = $header;
200         $new->headers[$header]         = $value;
201
202         return $new;
203     }
204
205     /**
206      * Return an instance with the specified header appended with the
207      * given value.
208      *
209      * Existing values for the specified header will be maintained. The new
210      * value(s) will be appended to the existing list. If the header did not
211      * exist previously, it will be added.
212      *
213      * This method MUST be implemented in such a way as to retain the
214      * immutability of the message, and MUST return an instance that has the
215      * new header and/or value.
216      *
217      * @param string $header Case-insensitive header field name to add.
218      * @param string|string[] $value Header value(s).
219      * @return static
220      * @throws \InvalidArgumentException for invalid header names or values.
221      */
222     public function withAddedHeader($header, $value)
223     {
224         $this->assertHeader($header);
225
226         if (! $this->hasHeader($header)) {
227             return $this->withHeader($header, $value);
228         }
229
230         $header = $this->headerNames[strtolower($header)];
231
232         $new = clone $this;
233         $value = $this->filterHeaderValue($value);
234         $new->headers[$header] = array_merge($this->headers[$header], $value);
235         return $new;
236     }
237
238     /**
239      * Return an instance without the specified header.
240      *
241      * Header resolution MUST be done without case-sensitivity.
242      *
243      * This method MUST be implemented in such a way as to retain the
244      * immutability of the message, and MUST return an instance that removes
245      * the named header.
246      *
247      * @param string $header Case-insensitive header field name to remove.
248      * @return static
249      */
250     public function withoutHeader($header)
251     {
252         if (! $this->hasHeader($header)) {
253             return clone $this;
254         }
255
256         $normalized = strtolower($header);
257         $original   = $this->headerNames[$normalized];
258
259         $new = clone $this;
260         unset($new->headers[$original], $new->headerNames[$normalized]);
261         return $new;
262     }
263
264     /**
265      * Gets the body of the message.
266      *
267      * @return StreamInterface Returns the body as a stream.
268      */
269     public function getBody()
270     {
271         return $this->stream;
272     }
273
274     /**
275      * Return an instance with the specified message body.
276      *
277      * The body MUST be a StreamInterface object.
278      *
279      * This method MUST be implemented in such a way as to retain the
280      * immutability of the message, and MUST return a new instance that has the
281      * new body stream.
282      *
283      * @param StreamInterface $body Body.
284      * @return static
285      * @throws \InvalidArgumentException When the body is not valid.
286      */
287     public function withBody(StreamInterface $body)
288     {
289         $new = clone $this;
290         $new->stream = $body;
291         return $new;
292     }
293
294     private function getStream($stream, $modeIfNotInstance)
295     {
296         if ($stream instanceof StreamInterface) {
297             return $stream;
298         }
299
300         if (! is_string($stream) && ! is_resource($stream)) {
301             throw new InvalidArgumentException(
302                 'Stream must be a string stream resource identifier, '
303                 . 'an actual stream resource, '
304                 . 'or a Psr\Http\Message\StreamInterface implementation'
305             );
306         }
307
308         return new Stream($stream, $modeIfNotInstance);
309     }
310
311     /**
312      * Filter a set of headers to ensure they are in the correct internal format.
313      *
314      * Used by message constructors to allow setting all initial headers at once.
315      *
316      * @param array $originalHeaders Headers to filter.
317      */
318     private function setHeaders(array $originalHeaders)
319     {
320         $headerNames = $headers = [];
321
322         foreach ($originalHeaders as $header => $value) {
323             $value = $this->filterHeaderValue($value);
324
325             $this->assertHeader($header);
326
327             $headerNames[strtolower($header)] = $header;
328             $headers[$header] = $value;
329         }
330
331         $this->headerNames = $headerNames;
332         $this->headers = $headers;
333     }
334
335     /**
336      * Validate the HTTP protocol version
337      *
338      * @param string $version
339      * @throws InvalidArgumentException on invalid HTTP protocol version
340      */
341     private function validateProtocolVersion($version)
342     {
343         if (empty($version)) {
344             throw new InvalidArgumentException(
345                 'HTTP protocol version can not be empty'
346             );
347         }
348         if (! is_string($version)) {
349             throw new InvalidArgumentException(sprintf(
350                 'Unsupported HTTP protocol version; must be a string, received %s',
351                 (is_object($version) ? get_class($version) : gettype($version))
352             ));
353         }
354
355         // HTTP/1 uses a "<major>.<minor>" numbering scheme to indicate
356         // versions of the protocol, while HTTP/2 does not.
357         if (! preg_match('#^(1\.[01]|2)$#', $version)) {
358             throw new InvalidArgumentException(sprintf(
359                 'Unsupported HTTP protocol version "%s" provided',
360                 $version
361             ));
362         }
363     }
364
365     /**
366      * @param mixed $values
367      * @return string[]
368      */
369     private function filterHeaderValue($values)
370     {
371         if (! is_array($values)) {
372             $values = [$values];
373         }
374
375         return array_map(function ($value) {
376             HeaderSecurity::assertValid($value);
377
378             return (string) $value;
379         }, $values);
380     }
381
382     /**
383      * Ensure header name and values are valid.
384      *
385      * @param string $name
386      *
387      * @throws InvalidArgumentException
388      */
389     private function assertHeader($name)
390     {
391         HeaderSecurity::assertValidName($name);
392     }
393 }