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