Passed
Pull Request — master (#19800)
by Paweł
14:47
created

Response::prepare()   B

Complexity

Conditions 11
Paths 21

Size

Total Lines 38
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 12.0935

Importance

Changes 0
Metric Value
cc 11
eloc 26
c 0
b 0
f 0
nc 21
nop 0
dl 0
loc 38
ccs 19
cts 24
cp 0.7917
crap 12.0935
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidRouteException;
14
use yii\helpers\FileHelper;
15
use yii\helpers\Inflector;
16
use yii\helpers\StringHelper;
17
use yii\helpers\Url;
18
19
/**
20
 * The web Response class represents an HTTP response.
21
 *
22
 * It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client.
23
 * It also controls the HTTP [[statusCode|status code]].
24
 *
25
 * Response is configured as an application component in [[\yii\web\Application]] by default.
26
 * You can access that instance via `Yii::$app->response`.
27
 *
28
 * You can modify its configuration by adding an array to your application config under `components`
29
 * as it is shown in the following example:
30
 *
31
 * ```php
32
 * 'response' => [
33
 *     'format' => yii\web\Response::FORMAT_JSON,
34
 *     'charset' => 'UTF-8',
35
 *     // ...
36
 * ]
37
 * ```
38
 *
39
 * For more details and usage information on Response, see the [guide article on responses](guide:runtime-responses).
40
 *
41
 * @property-read CookieCollection $cookies The cookie collection.
42
 * @property-write string $downloadHeaders The attachment file name.
43
 * @property-read HeaderCollection $headers The header collection.
44
 * @property-read bool $isClientError Whether this response indicates a client error.
45
 * @property-read bool $isEmpty Whether this response is empty.
46
 * @property-read bool $isForbidden Whether this response indicates the current request is forbidden.
47
 * @property-read bool $isInformational Whether this response is informational.
48
 * @property-read bool $isInvalid Whether this response has a valid [[statusCode]].
49
 * @property-read bool $isNotFound Whether this response indicates the currently requested resource is not
50
 * found.
51
 * @property-read bool $isOk Whether this response is OK.
52
 * @property-read bool $isRedirection Whether this response is a redirection.
53
 * @property-read bool $isServerError Whether this response indicates a server error.
54
 * @property-read bool $isSuccessful Whether this response is successful.
55
 * @property int $statusCode The HTTP status code to send with the response.
56
 * @property-write \Throwable $statusCodeByException The exception object.
57
 *
58
 * @author Qiang Xue <[email protected]>
59
 * @author Carsten Brandt <[email protected]>
60
 * @since 2.0
61
 */
62
class Response extends \yii\base\Response
63
{
64
    /**
65
     * @event \yii\base\Event an event that is triggered at the beginning of [[send()]].
66
     */
67
    const EVENT_BEFORE_SEND = 'beforeSend';
68
    /**
69
     * @event \yii\base\Event an event that is triggered at the end of [[send()]].
70
     */
71
    const EVENT_AFTER_SEND = 'afterSend';
72
    /**
73
     * @event \yii\base\Event an event that is triggered right after [[prepare()]] is called in [[send()]].
74
     * You may respond to this event to filter the response content before it is sent to the client.
75
     */
76
    const EVENT_AFTER_PREPARE = 'afterPrepare';
77
    const FORMAT_RAW = 'raw';
78
    const FORMAT_HTML = 'html';
79
    const FORMAT_JSON = 'json';
80
    const FORMAT_JSONP = 'jsonp';
81
    const FORMAT_XML = 'xml';
82
83
    /**
84
     * @var string the response format. This determines how to convert [[data]] into [[content]]
85
     * when the latter is not set. The value of this property must be one of the keys declared in the [[formatters]] array.
86
     * By default, the following formats are supported:
87
     *
88
     * - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
89
     *   No extra HTTP header will be added.
90
     * - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
91
     *   The "Content-Type" header will set as "text/html".
92
     * - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
93
     *   header will be set as "application/json".
94
     * - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
95
     *   header will be set as "text/javascript". Note that in this case `$data` must be an array
96
     *   with "data" and "callback" elements. The former refers to the actual data to be sent,
97
     *   while the latter refers to the name of the JavaScript callback.
98
     * - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
99
     *   for more details.
100
     *
101
     * You may customize the formatting process or support additional formats by configuring [[formatters]].
102
     * @see formatters
103
     */
104
    public $format = self::FORMAT_HTML;
105
    /**
106
     * @var string the MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response.
107
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
108
     */
109
    public $acceptMimeType;
110
    /**
111
     * @var array the parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [[acceptMimeType|chosen MIME type]].
112
     * This is a list of name-value pairs associated with [[acceptMimeType]] from the ACCEPT HTTP header.
113
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
114
     */
115
    public $acceptParams = [];
116
    /**
117
     * @var array the formatters for converting data into the response content of the specified [[format]].
118
     * The array keys are the format names, and the array values are the corresponding configurations
119
     * for creating the formatter objects.
120
     * @see format
121
     * @see defaultFormatters
122
     */
123
    public $formatters = [];
124
    /**
125
     * @var mixed the original response data. When this is not null, it will be converted into [[content]]
126
     * according to [[format]] when the response is being sent out.
127
     * @see content
128
     */
129
    public $data;
130
    /**
131
     * @var string|null the response content. When [[data]] is not null, it will be converted into [[content]]
132
     * according to [[format]] when the response is being sent out.
133
     * @see data
134
     */
135
    public $content;
136
    /**
137
     * @var resource|array|callable the stream to be sent. This can be a stream handle or an array of stream handle,
138
     * the begin position and the end position. Alternatively it can be set to a callable, which returns
139
     * (or [yields](https://www.php.net/manual/en/language.generators.syntax.php)) an array of strings that should
140
     * be echoed and flushed out one by one.
141
     *
142
     * Note that when this property is set, the [[data]] and [[content]] properties will be ignored by [[send()]].
143
     */
144
    public $stream;
145
    /**
146
     * @var string|null the charset of the text response. If not set, it will use
147
     * the value of [[Application::charset]].
148
     */
149
    public $charset;
150
    /**
151
     * @var string the HTTP status description that comes together with the status code.
152
     * @see httpStatuses
153
     */
154
    public $statusText = 'OK';
155
    /**
156
     * @var string|null the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`,
157
     * or '1.1' if that is not available.
158
     */
159
    public $version;
160
    /**
161
     * @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing.
162
     */
163
    public $isSent = false;
164
    /**
165
     * @var array list of HTTP status codes and the corresponding texts
166
     */
167
    public static $httpStatuses = [
168
        100 => 'Continue',
169
        101 => 'Switching Protocols',
170
        102 => 'Processing',
171
        118 => 'Connection timed out',
172
        200 => 'OK',
173
        201 => 'Created',
174
        202 => 'Accepted',
175
        203 => 'Non-Authoritative',
176
        204 => 'No Content',
177
        205 => 'Reset Content',
178
        206 => 'Partial Content',
179
        207 => 'Multi-Status',
180
        208 => 'Already Reported',
181
        210 => 'Content Different',
182
        226 => 'IM Used',
183
        300 => 'Multiple Choices',
184
        301 => 'Moved Permanently',
185
        302 => 'Found',
186
        303 => 'See Other',
187
        304 => 'Not Modified',
188
        305 => 'Use Proxy',
189
        306 => 'Reserved',
190
        307 => 'Temporary Redirect',
191
        308 => 'Permanent Redirect',
192
        310 => 'Too many Redirect',
193
        400 => 'Bad Request',
194
        401 => 'Unauthorized',
195
        402 => 'Payment Required',
196
        403 => 'Forbidden',
197
        404 => 'Not Found',
198
        405 => 'Method Not Allowed',
199
        406 => 'Not Acceptable',
200
        407 => 'Proxy Authentication Required',
201
        408 => 'Request Time-out',
202
        409 => 'Conflict',
203
        410 => 'Gone',
204
        411 => 'Length Required',
205
        412 => 'Precondition Failed',
206
        413 => 'Request Entity Too Large',
207
        414 => 'Request-URI Too Long',
208
        415 => 'Unsupported Media Type',
209
        416 => 'Requested range unsatisfiable',
210
        417 => 'Expectation failed',
211
        418 => 'I\'m a teapot',
212
        421 => 'Misdirected Request',
213
        422 => 'Unprocessable entity',
214
        423 => 'Locked',
215
        424 => 'Method failure',
216
        425 => 'Unordered Collection',
217
        426 => 'Upgrade Required',
218
        428 => 'Precondition Required',
219
        429 => 'Too Many Requests',
220
        431 => 'Request Header Fields Too Large',
221
        449 => 'Retry With',
222
        450 => 'Blocked by Windows Parental Controls',
223
        451 => 'Unavailable For Legal Reasons',
224
        500 => 'Internal Server Error',
225
        501 => 'Not Implemented',
226
        502 => 'Bad Gateway or Proxy Error',
227
        503 => 'Service Unavailable',
228
        504 => 'Gateway Time-out',
229
        505 => 'HTTP Version not supported',
230
        507 => 'Insufficient storage',
231
        508 => 'Loop Detected',
232
        509 => 'Bandwidth Limit Exceeded',
233
        510 => 'Not Extended',
234
        511 => 'Network Authentication Required',
235
    ];
236
237
    /**
238
     * @var int the HTTP status code to send with the response.
239
     */
240
    private $_statusCode = 200;
241
    /**
242
     * @var HeaderCollection
243
     */
244
    private $_headers;
245
246
247
    /**
248
     * Initializes this component.
249
     */
250 353
    public function init()
251
    {
252 353
        if ($this->version === null) {
253 353
            if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
254
                $this->version = '1.0';
255
            } else {
256 353
                $this->version = '1.1';
257
            }
258
        }
259 353
        if ($this->charset === null) {
260 353
            $this->charset = Yii::$app->charset;
261
        }
262 353
        $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
263 353
    }
264
265
    /**
266
     * @return int the HTTP status code to send with the response.
267
     */
268 63
    public function getStatusCode()
269
    {
270 63
        return $this->_statusCode;
271
    }
272
273
    /**
274
     * Sets the response status code.
275
     * This method will set the corresponding status text if `$text` is null.
276
     * @param int $value the status code
277
     * @param string|null $text the status text. If not set, it will be set automatically based on the status code.
278
     * @throws InvalidArgumentException if the status code is invalid.
279
     * @return $this the response object itself
280
     */
281 56
    public function setStatusCode($value, $text = null)
282
    {
283 56
        if ($value === null) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
284
            $value = 200;
285
        }
286 56
        $this->_statusCode = (int) $value;
287 56
        if ($this->getIsInvalid()) {
288
            throw new InvalidArgumentException("The HTTP status code is invalid: $value");
289
        }
290 56
        if ($text === null) {
291 52
            $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
292
        } else {
293 4
            $this->statusText = $text;
294
        }
295
296 56
        return $this;
297
    }
298
299
    /**
300
     * Sets the response status code based on the exception.
301
     * @param \Throwable $e the exception object.
302
     * @throws InvalidArgumentException if the status code is invalid.
303
     * @return $this the response object itself
304
     * @since 2.0.12
305
     */
306 18
    public function setStatusCodeByException($e)
307
    {
308 18
        if ($e instanceof HttpException) {
309 10
            $this->setStatusCode($e->statusCode);
310
        } else {
311 8
            $this->setStatusCode(500);
312
        }
313
314 18
        return $this;
315
    }
316
317
    /**
318
     * Returns the header collection.
319
     * The header collection contains the currently registered HTTP headers.
320
     * @return HeaderCollection the header collection
321
     */
322 129
    public function getHeaders()
323
    {
324 129
        if ($this->_headers === null) {
325 129
            $this->_headers = new HeaderCollection();
326
        }
327
328 129
        return $this->_headers;
329
    }
330
331
    /**
332
     * Sends the response to the client.
333
     */
334 36
    public function send()
335
    {
336 36
        if ($this->isSent) {
337 3
            return;
338
        }
339 36
        $this->trigger(self::EVENT_BEFORE_SEND);
340 36
        $this->prepare();
341 36
        $this->trigger(self::EVENT_AFTER_PREPARE);
342 36
        $this->sendHeaders();
343 36
        $this->sendContent();
344 36
        $this->trigger(self::EVENT_AFTER_SEND);
345 36
        $this->isSent = true;
346 36
    }
347
348
    /**
349
     * Clears the headers, cookies, content, status code of the response.
350
     */
351
    public function clear()
352
    {
353
        $this->_headers = null;
354
        $this->_cookies = null;
355
        $this->_statusCode = 200;
356
        $this->statusText = 'OK';
357
        $this->data = null;
358
        $this->stream = null;
359
        $this->content = null;
360
        $this->isSent = false;
361
    }
362
363
    /**
364
     * Sends the response headers to the client.
365
     */
366 36
    protected function sendHeaders()
367
    {
368 36
        if (headers_sent($file, $line)) {
369
            throw new HeadersAlreadySentException($file, $line);
370
        }
371 36
        if ($this->_headers) {
372 31
            foreach ($this->getHeaders() as $name => $values) {
373 31
                $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
374
                // set replace for first occurrence of header but false afterwards to allow multiple
375 31
                $replace = true;
376 31
                foreach ($values as $value) {
377 31
                    header("$name: $value", $replace);
378 31
                    $replace = false;
379
                }
380
            }
381
        }
382 36
        $statusCode = $this->getStatusCode();
383 36
        header("HTTP/{$this->version} {$statusCode} {$this->statusText}");
384 36
        $this->sendCookies();
385 36
    }
386
387
    /**
388
     * Sends the cookies to the client.
389
     */
390 36
    protected function sendCookies()
391
    {
392 36
        if ($this->_cookies === null) {
393 31
            return;
394
        }
395 5
        $request = Yii::$app->getRequest();
396 5
        if ($request->enableCookieValidation) {
0 ignored issues
show
Bug Best Practice introduced by
The property enableCookieValidation does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
397 5
            if ($request->cookieValidationKey == '') {
0 ignored issues
show
Bug Best Practice introduced by
The property cookieValidationKey does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
398
                throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
399
            }
400 5
            $validationKey = $request->cookieValidationKey;
401
        }
402 5
        foreach ($this->getCookies() as $cookie) {
403 5
            $value = $cookie->value;
404 5
            if ($cookie->expire != 1 && isset($validationKey)) {
405 5
                $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
406
            }
407 5
            if (PHP_VERSION_ID >= 70300) {
408 5
                setcookie($cookie->name, $value, [
409 5
                    'expires' => $cookie->expire,
410 5
                    'path' => $cookie->path,
411 5
                    'domain' => $cookie->domain,
412 5
                    'secure' => $cookie->secure,
413 5
                    'httpOnly' => $cookie->httpOnly,
414 5
                    'sameSite' => !empty($cookie->sameSite) ? $cookie->sameSite : null,
415
                ]);
416
            } else {
417
                // Work around for setting sameSite cookie prior PHP 7.3
418
                // https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict/46971326#46971326
419
                $cookiePath = $cookie->path;
420
                if (!is_null($cookie->sameSite)) {
421
                    $cookiePath .= '; samesite=' . $cookie->sameSite;
422
                }
423
                setcookie($cookie->name, $value, $cookie->expire, $cookiePath, $cookie->domain, $cookie->secure, $cookie->httpOnly);
424
            }
425
        }
426 5
    }
427
428
    /**
429
     * Sends the response content to the client.
430
     */
431 36
    protected function sendContent()
432
    {
433 36
        if ($this->stream === null) {
434 32
            echo $this->content;
435
436 32
            return;
437
        }
438
439
        // Try to reset time limit for big files
440 4
        if (!function_exists('set_time_limit') || !@set_time_limit(0)) {
441
            Yii::warning('set_time_limit() is not available', __METHOD__);
442
        }
443
444 4
        if (is_callable($this->stream)) {
445
            $data = call_user_func($this->stream);
0 ignored issues
show
Bug introduced by
It seems like $this->stream can also be of type resource; however, parameter $callback of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

445
            $data = call_user_func(/** @scrutinizer ignore-type */ $this->stream);
Loading history...
446
            foreach ($data as $datum) {
447
                echo $datum;
448
                flush();
449
            }
450
            return;
451
        }
452
453 4
        $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
454
455 4
        if (is_array($this->stream)) {
456 4
            list($handle, $begin, $end) = $this->stream;
457
458
            // only seek if stream is seekable
459 4
            if ($this->isSeekable($handle)) {
460 3
                fseek($handle, $begin);
461
            }
462
463 4
            while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
464 3
                if ($pos + $chunkSize > $end) {
465 3
                    $chunkSize = $end - $pos + 1;
466
                }
467 3
                echo fread($handle, $chunkSize);
468 3
                flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
469
            }
470 4
            fclose($handle);
471
        } else {
472
            while (!feof($this->stream)) {
0 ignored issues
show
Bug introduced by
It seems like $this->stream can also be of type callable; however, parameter $stream of feof() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

472
            while (!feof(/** @scrutinizer ignore-type */ $this->stream)) {
Loading history...
473
                echo fread($this->stream, $chunkSize);
0 ignored issues
show
Bug introduced by
It seems like $this->stream can also be of type callable; however, parameter $stream of fread() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

473
                echo fread(/** @scrutinizer ignore-type */ $this->stream, $chunkSize);
Loading history...
474
                flush();
475
            }
476
            fclose($this->stream);
0 ignored issues
show
Bug introduced by
It seems like $this->stream can also be of type callable; however, parameter $stream of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

476
            fclose(/** @scrutinizer ignore-type */ $this->stream);
Loading history...
477
        }
478 4
    }
479
480
    /**
481
     * Sends a file to the browser.
482
     *
483
     * Note that this method only prepares the response for file sending. The file is not sent
484
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
485
     *
486
     * The following is an example implementation of a controller action that allows requesting files from a directory
487
     * that is not accessible from web:
488
     *
489
     * ```php
490
     * public function actionFile($filename)
491
     * {
492
     *     $storagePath = Yii::getAlias('@app/files');
493
     *
494
     *     // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
495
     *     if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
496
     *         throw new \yii\web\NotFoundHttpException('The file does not exists.');
497
     *     }
498
     *     return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
499
     * }
500
     * ```
501
     *
502
     * @param string $filePath the path of the file to be sent.
503
     * @param string|null $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
504
     * @param array $options additional options for sending the file. The following options are supported:
505
     *
506
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
507
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
508
     *    meaning a download dialog will pop up.
509
     *
510
     * @return $this the response object itself
511
     * @see sendContentAsFile()
512
     * @see sendStreamAsFile()
513
     * @see xSendFile()
514
     */
515 10
    public function sendFile($filePath, $attachmentName = null, $options = [])
516
    {
517 10
        if (!isset($options['mimeType'])) {
518 10
            $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
519
        }
520 10
        if ($attachmentName === null) {
521 9
            $attachmentName = basename($filePath);
522
        }
523 10
        $handle = fopen($filePath, 'rb');
524 10
        $this->sendStreamAsFile($handle, $attachmentName, $options);
525
526 6
        return $this;
527
    }
528
529
    /**
530
     * Sends the specified content as a file to the browser.
531
     *
532
     * Note that this method only prepares the response for file sending. The file is not sent
533
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
534
     *
535
     * @param string $content the content to be sent. The existing [[content]] will be discarded.
536
     * @param string $attachmentName the file name shown to the user.
537
     * @param array $options additional options for sending the file. The following options are supported:
538
     *
539
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
540
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
541
     *    meaning a download dialog will pop up.
542
     *
543
     * @return $this the response object itself
544
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
545
     * @see sendFile() for an example implementation.
546
     */
547 1
    public function sendContentAsFile($content, $attachmentName, $options = [])
548
    {
549 1
        $headers = $this->getHeaders();
550
551 1
        $contentLength = StringHelper::byteLength($content);
552 1
        $range = $this->getHttpRange($contentLength);
553
554 1
        if ($range === false) {
0 ignored issues
show
introduced by
The condition $range === false is always false.
Loading history...
555
            $headers->set('Content-Range', "bytes */$contentLength");
556
            throw new RangeNotSatisfiableHttpException();
557
        }
558
559 1
        list($begin, $end) = $range;
560 1
        if ($begin != 0 || $end != $contentLength - 1) {
561
            $this->setStatusCode(206);
562
            $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
563
            $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
564
        } else {
565 1
            $this->setStatusCode(200);
566 1
            $this->content = $content;
567
        }
568
569 1
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
570 1
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
571
572 1
        $this->format = self::FORMAT_RAW;
573
574 1
        return $this;
575
    }
576
577
    /**
578
     * Sends the specified stream as a file to the browser.
579
     *
580
     * Note that this method only prepares the response for file sending. The file is not sent
581
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
582
     *
583
     * @param resource $handle the handle of the stream to be sent.
584
     * @param string $attachmentName the file name shown to the user.
585
     * @param array $options additional options for sending the file. The following options are supported:
586
     *
587
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
588
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
589
     *    meaning a download dialog will pop up.
590
     *  - `fileSize`: the size of the content to stream this is useful when size of the content is known
591
     *    and the content is not seekable. Defaults to content size using `ftell()`.
592
     *    This option is available since version 2.0.4.
593
     *
594
     * @return $this the response object itself
595
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
596
     * @see sendFile() for an example implementation.
597
     */
598 11
    public function sendStreamAsFile($handle, $attachmentName, $options = [])
599
    {
600 11
        $headers = $this->getHeaders();
601 11
        if (isset($options['fileSize'])) {
602
            $fileSize = $options['fileSize'];
603
        } else {
604 11
            if ($this->isSeekable($handle)) {
605 10
                fseek($handle, 0, SEEK_END);
606 10
                $fileSize = ftell($handle);
607
            } else {
608 1
                $fileSize = 0;
609
            }
610
        }
611
612 11
        $range = $this->getHttpRange($fileSize);
613 11
        if ($range === false) {
0 ignored issues
show
introduced by
The condition $range === false is always false.
Loading history...
614 4
            $headers->set('Content-Range', "bytes */$fileSize");
615 4
            throw new RangeNotSatisfiableHttpException();
616
        }
617
618 7
        list($begin, $end) = $range;
619 7
        if ($begin != 0 || $end != $fileSize - 1) {
620 3
            $this->setStatusCode(206);
621 3
            $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
622
        } else {
623 4
            $this->setStatusCode(200);
624
        }
625
626 7
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
627 7
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
628
629 7
        $this->format = self::FORMAT_RAW;
630 7
        $this->stream = [$handle, $begin, $end];
631
632 7
        return $this;
633
    }
634
635
    /**
636
     * Sets a default set of HTTP headers for file downloading purpose.
637
     * @param string $attachmentName the attachment file name
638
     * @param string|null $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
639
     * @param bool $inline whether the browser should open the file within the browser window. Defaults to false,
640
     * meaning a download dialog will pop up.
641
     * @param int|null $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
642
     * @return $this the response object itself
643
     */
644 8
    public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
645
    {
646 8
        $headers = $this->getHeaders();
647
648 8
        $disposition = $inline ? 'inline' : 'attachment';
649 8
        $headers->setDefault('Pragma', 'public')
650 8
            ->setDefault('Accept-Ranges', 'bytes')
651 8
            ->setDefault('Expires', '0')
652 8
            ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
653 8
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
654
655 8
        if ($mimeType !== null) {
656 8
            $headers->setDefault('Content-Type', $mimeType);
657
        }
658
659 8
        if ($contentLength !== null) {
660 8
            $headers->setDefault('Content-Length', $contentLength);
661
        }
662
663 8
        return $this;
664
    }
665
666
    /**
667
     * Determines the HTTP range given in the request.
668
     * @param int $fileSize the size of the file that will be used to validate the requested HTTP range.
669
     * @return array|bool the range (begin, end), or false if the range request is invalid.
670
     */
671 12
    protected function getHttpRange($fileSize)
672
    {
673 12
        $rangeHeader = Yii::$app->getRequest()->getHeaders()->get('Range', '-');
0 ignored issues
show
Bug introduced by
The method getHeaders() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

673
        $rangeHeader = Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getHeaders()->get('Range', '-');
Loading history...
674 12
        if ($rangeHeader === '-') {
675 5
            return [0, $fileSize - 1];
676
        }
677 7
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) {
0 ignored issues
show
Bug introduced by
It seems like $rangeHeader can also be of type array and null; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

677
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', /** @scrutinizer ignore-type */ $rangeHeader, $matches)) {
Loading history...
678 1
            return false;
679
        }
680 6
        if ($matches[1] === '') {
681 2
            $start = $fileSize - $matches[2];
682 2
            $end = $fileSize - 1;
683 4
        } elseif ($matches[2] !== '') {
684 2
            $start = $matches[1];
685 2
            $end = $matches[2];
686 2
            if ($end >= $fileSize) {
687 2
                $end = $fileSize - 1;
688
            }
689
        } else {
690 2
            $start = $matches[1];
691 2
            $end = $fileSize - 1;
692
        }
693 6
        if ($start < 0 || $start > $end) {
694 3
            return false;
695
        }
696
697 3
        return [$start, $end];
698
    }
699
700
    /**
701
     * Sends existing file to a browser as a download using x-sendfile.
702
     *
703
     * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
704
     * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
705
     * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
706
     * increase in performance as the web application is allowed to terminate earlier while the webserver is
707
     * handling the request.
708
     *
709
     * The request is sent to the server through a special non-standard HTTP-header.
710
     * When the web server encounters the presence of such header it will discard all output and send the file
711
     * specified by that header using web server internals including all optimizations like caching-headers.
712
     *
713
     * As this header directive is non-standard different directives exists for different web servers applications:
714
     *
715
     * - Apache: [X-Sendfile](https://tn123.org/mod_xsendfile/)
716
     * - Lighttpd v1.4: [X-LIGHTTPD-send-file](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
717
     * - Lighttpd v1.5: [X-Sendfile](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
718
     * - Nginx: [X-Accel-Redirect](https://www.nginx.com/resources/wiki/XSendfile)
719
     * - Cherokee: [X-Sendfile and X-Accel-Redirect](https://cherokee-project.com/doc/other_goodies.html#x-sendfile)
720
     *
721
     * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
722
     * a proper xHeader should be sent.
723
     *
724
     * **Note**
725
     *
726
     * This option allows to download files that are not under web folders, and even files that are otherwise protected
727
     * (deny from all) like `.htaccess`.
728
     *
729
     * **Side effects**
730
     *
731
     * If this option is disabled by the web server, when this method is called a download configuration dialog
732
     * will open but the downloaded file will have 0 bytes.
733
     *
734
     * **Known issues**
735
     *
736
     * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
737
     * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
738
     * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
739
     *
740
     * **Example**
741
     *
742
     * ```php
743
     * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
744
     * ```
745
     *
746
     * @param string $filePath file name with full path
747
     * @param string|null $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
748
     * @param array $options additional options for sending the file. The following options are supported:
749
     *
750
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
751
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
752
     *    meaning a download dialog will pop up.
753
     *  - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
754
     *
755
     * @return $this the response object itself
756
     * @see sendFile()
757
     */
758
    public function xSendFile($filePath, $attachmentName = null, $options = [])
759
    {
760
        if ($attachmentName === null) {
761
            $attachmentName = basename($filePath);
762
        }
763
        if (isset($options['mimeType'])) {
764
            $mimeType = $options['mimeType'];
765
        } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
766
            $mimeType = 'application/octet-stream';
767
        }
768
        if (isset($options['xHeader'])) {
769
            $xHeader = $options['xHeader'];
770
        } else {
771
            $xHeader = 'X-Sendfile';
772
        }
773
774
        $disposition = empty($options['inline']) ? 'attachment' : 'inline';
775
        $this->getHeaders()
776
            ->setDefault($xHeader, $filePath)
777
            ->setDefault('Content-Type', $mimeType)
778
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
779
780
        $this->format = self::FORMAT_RAW;
781
782
        return $this;
783
    }
784
785
    /**
786
     * Returns Content-Disposition header value that is safe to use with both old and new browsers.
787
     *
788
     * Fallback name:
789
     *
790
     * - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
791
     * - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret
792
     *   `filename="X"` as urlencoded name, some don't.
793
     * - Causes issues if contains path separator characters such as `\` or `/`.
794
     * - Since value is wrapped with `"`, it should be escaped as `\"`.
795
     * - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
796
     *
797
     * UTF name:
798
     *
799
     * - Causes issues if contains path separator characters such as `\` or `/`.
800
     * - Should be urlencoded since headers are ASCII-only.
801
     * - Could be omitted if it exactly matches fallback name.
802
     *
803
     * @param string $disposition
804
     * @param string $attachmentName
805
     * @return string
806
     *
807
     * @since 2.0.10
808
     */
809 8
    protected function getDispositionHeaderValue($disposition, $attachmentName)
810
    {
811 8
        $fallbackName = str_replace(
812 8
            ['%', '/', '\\', '"', "\x7F"],
813 8
            ['_', '_', '_', '\\"', '_'],
814 8
            Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)
815
        );
816 8
        $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
817
818 8
        $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
819 8
        if ($utfName !== $fallbackName) {
820 1
            $dispositionHeader .= "; filename*=utf-8''{$utfName}";
821
        }
822
823 8
        return $dispositionHeader;
824
    }
825
826
    /**
827
     * Redirects the browser to the specified URL.
828
     *
829
     * This method adds a "Location" header to the current response. Note that it does not send out
830
     * the header until [[send()]] is called. In a controller action you may use this method as follows:
831
     *
832
     * ```php
833
     * return Yii::$app->getResponse()->redirect($url);
834
     * ```
835
     *
836
     * In other places, if you want to send out the "Location" header immediately, you should use
837
     * the following code:
838
     *
839
     * ```php
840
     * Yii::$app->getResponse()->redirect($url)->send();
841
     * return;
842
     * ```
843
     *
844
     * In AJAX mode, this normally will not work as expected unless there are some
845
     * client-side JavaScript code handling the redirection. To help achieve this goal,
846
     * this method will send out a "X-Redirect" header instead of "Location".
847
     *
848
     * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
849
     * described above. Otherwise, you should write the following JavaScript code to
850
     * handle the redirection:
851
     *
852
     * ```javascript
853
     * $document.ajaxComplete(function (event, xhr, settings) {
854
     *     var url = xhr && xhr.getResponseHeader('X-Redirect');
855
     *     if (url) {
856
     *         window.location = url;
857
     *     }
858
     * });
859
     * ```
860
     *
861
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
862
     *
863
     * - a string representing a URL (e.g. "https://example.com")
864
     * - a string representing a URL alias (e.g. "@example.com")
865
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
866
     *   Note that the route is with respect to the whole application, instead of relative to a controller or module.
867
     *   [[Url::to()]] will be used to convert the array into a URL.
868
     *
869
     * Any relative URL that starts with a single forward slash "/" will be converted
870
     * into an absolute one by prepending it with the host info of the current request.
871
     *
872
     * @param int $statusCode the HTTP status code. Defaults to 302.
873
     * See <https://tools.ietf.org/html/rfc2616#section-10>
874
     * for details about HTTP status code
875
     * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
876
     * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
877
     * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
878
     * an AJAX/PJAX response, may NOT cause browser redirection.
879
     * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
880
     * @return $this the response object itself
881
     */
882 10
    public function redirect($url, $statusCode = 302, $checkAjax = true)
883
    {
884 10
        if (is_array($url) && isset($url[0])) {
885
            // ensure the route is absolute
886 8
            $url[0] = '/' . ltrim($url[0], '/');
887
        }
888 10
        $request = Yii::$app->getRequest();
889 10
        $normalizedUrl = Url::to($url);
890 10
        if ($normalizedUrl !== null) {
0 ignored issues
show
introduced by
The condition $normalizedUrl !== null is always true.
Loading history...
891 10
            if (\preg_match('/\n/', $normalizedUrl)) {
892 1
                throw new InvalidRouteException('Route with new line character detected "' . $normalizedUrl . '".');
893
            }
894 9
            if (strncmp($normalizedUrl, '/', 1) === 0 && strncmp($normalizedUrl, '//', 2) !== 0) {
895 9
                $normalizedUrl = $request->getHostInfo() . $normalizedUrl;
0 ignored issues
show
Bug introduced by
The method getHostInfo() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

895
                $normalizedUrl = $request->/** @scrutinizer ignore-call */ getHostInfo() . $normalizedUrl;
Loading history...
896
            }
897
        }
898
899 9
        if ($checkAjax && $request->getIsAjax()) {
0 ignored issues
show
Bug introduced by
The method getIsAjax() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

899
        if ($checkAjax && $request->/** @scrutinizer ignore-call */ getIsAjax()) {
Loading history...
900
            if (
901 7
                in_array($statusCode, [301, 302])
902 7
                && preg_match('/Trident\/|MSIE /', (string)$request->userAgent)
0 ignored issues
show
Bug Best Practice introduced by
The property userAgent does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
903
            ) {
904 3
                $statusCode = 200;
905
            }
906 7
            if ($request->getIsPjax()) {
0 ignored issues
show
Bug introduced by
The method getIsPjax() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

906
            if ($request->/** @scrutinizer ignore-call */ getIsPjax()) {
Loading history...
907 6
                $this->getHeaders()->set('X-Pjax-Url', $normalizedUrl);
908
            } else {
909 7
                $this->getHeaders()->set('X-Redirect', $normalizedUrl);
910
            }
911
        } else {
912 3
            $this->getHeaders()->set('Location', $normalizedUrl);
913
        }
914
915 9
        $this->setStatusCode($statusCode);
916
917 9
        return $this;
918
    }
919
920
    /**
921
     * Refreshes the current page.
922
     * The effect of this method call is the same as the user pressing the refresh button of his browser
923
     * (without re-posting data).
924
     *
925
     * In a controller action you may use this method like this:
926
     *
927
     * ```php
928
     * return Yii::$app->getResponse()->refresh();
929
     * ```
930
     *
931
     * @param string $anchor the anchor that should be appended to the redirection URL.
932
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
933
     * @return Response the response object itself
934
     */
935
    public function refresh($anchor = '')
936
    {
937
        return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
0 ignored issues
show
Bug introduced by
The method getUrl() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

937
        return $this->redirect(Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getUrl() . $anchor);
Loading history...
938
    }
939
940
    private $_cookies;
941
942
    /**
943
     * Returns the cookie collection.
944
     *
945
     * Through the returned cookie collection, you add or remove cookies as follows,
946
     *
947
     * ```php
948
     * // add a cookie
949
     * $response->cookies->add(new Cookie([
950
     *     'name' => $name,
951
     *     'value' => $value,
952
     * ]);
953
     *
954
     * // remove a cookie
955
     * $response->cookies->remove('name');
956
     * // alternatively
957
     * unset($response->cookies['name']);
958
     * ```
959
     *
960
     * @return CookieCollection the cookie collection.
961
     */
962 87
    public function getCookies()
963
    {
964 87
        if ($this->_cookies === null) {
965 87
            $this->_cookies = new CookieCollection();
966
        }
967
968 87
        return $this->_cookies;
969
    }
970
971
    /**
972
     * @return bool whether this response has a valid [[statusCode]].
973
     */
974 56
    public function getIsInvalid()
975
    {
976 56
        return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
977
    }
978
979
    /**
980
     * @return bool whether this response is informational
981
     */
982
    public function getIsInformational()
983
    {
984
        return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
985
    }
986
987
    /**
988
     * @return bool whether this response is successful
989
     */
990
    public function getIsSuccessful()
991
    {
992
        return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
993
    }
994
995
    /**
996
     * @return bool whether this response is a redirection
997
     */
998 1
    public function getIsRedirection()
999
    {
1000 1
        return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
1001
    }
1002
1003
    /**
1004
     * @return bool whether this response indicates a client error
1005
     */
1006
    public function getIsClientError()
1007
    {
1008
        return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
1009
    }
1010
1011
    /**
1012
     * @return bool whether this response indicates a server error
1013
     */
1014
    public function getIsServerError()
1015
    {
1016
        return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
1017
    }
1018
1019
    /**
1020
     * @return bool whether this response is OK
1021
     */
1022
    public function getIsOk()
1023
    {
1024
        return $this->getStatusCode() == 200;
1025
    }
1026
1027
    /**
1028
     * @return bool whether this response indicates the current request is forbidden
1029
     */
1030
    public function getIsForbidden()
1031
    {
1032
        return $this->getStatusCode() == 403;
1033
    }
1034
1035
    /**
1036
     * @return bool whether this response indicates the currently requested resource is not found
1037
     */
1038
    public function getIsNotFound()
1039
    {
1040
        return $this->getStatusCode() == 404;
1041
    }
1042
1043
    /**
1044
     * @return bool whether this response is empty
1045
     */
1046
    public function getIsEmpty()
1047
    {
1048
        return in_array($this->getStatusCode(), [201, 204, 304]);
1049
    }
1050
1051
    /**
1052
     * @return array the formatters that are supported by default
1053
     */
1054 353
    protected function defaultFormatters()
1055
    {
1056
        return [
1057 353
            self::FORMAT_HTML => [
1058 353
                'class' => 'yii\web\HtmlResponseFormatter',
1059
            ],
1060 353
            self::FORMAT_XML => [
1061
                'class' => 'yii\web\XmlResponseFormatter',
1062
            ],
1063 353
            self::FORMAT_JSON => [
1064
                'class' => 'yii\web\JsonResponseFormatter',
1065
            ],
1066 353
            self::FORMAT_JSONP => [
1067
                'class' => 'yii\web\JsonResponseFormatter',
1068
                'useJsonp' => true,
1069
            ],
1070
        ];
1071
    }
1072
1073
    /**
1074
     * Prepares for sending the response.
1075
     * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
1076
     * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
1077
     *
1078
     * @see https://tools.ietf.org/html/rfc7231#page-53
1079
     * @see https://tools.ietf.org/html/rfc7232#page-18
1080
     */
1081 36
    protected function prepare()
1082
    {
1083 36
        if (in_array($this->getStatusCode(), [204, 304])) {
1084
            // A 204/304 response cannot contain a message body according to rfc7231/rfc7232
1085 6
            $this->content = '';
1086 6
            $this->stream = null;
1087 6
            return;
1088
        }
1089
1090 30
        if ($this->stream !== null) {
1091 4
            return;
1092
        }
1093
1094 26
        if (isset($this->formatters[$this->format])) {
1095 24
            $formatter = $this->formatters[$this->format];
1096 24
            if (!is_object($formatter)) {
1097 24
                $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
1098
            }
1099 24
            if ($formatter instanceof ResponseFormatterInterface) {
1100 24
                $formatter->format($this);
1101
            } else {
1102 24
                throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
1103
            }
1104 2
        } elseif ($this->format === self::FORMAT_RAW) {
1105 2
            if ($this->data !== null) {
1106 2
                $this->content = $this->data;
1107
            }
1108
        } else {
1109
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
1110
        }
1111
1112 26
        if (is_array($this->content)) {
0 ignored issues
show
introduced by
The condition is_array($this->content) is always false.
Loading history...
1113
            throw new InvalidArgumentException('Response content must not be an array.');
1114 26
        } elseif (is_object($this->content)) {
1115
            if (method_exists($this->content, '__toString')) {
1116
                $this->content = $this->content->__toString();
1117
            } else {
1118
                throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
1119
            }
1120
        }
1121 26
    }
1122
1123
    /**
1124
     * Checks if a stream is seekable
1125
     *
1126
     * @param $handle
1127
     * @return bool
1128
     */
1129 11
    private function isSeekable($handle)
1130
    {
1131 11
        if (!is_resource($handle)) {
1132
            return true;
1133
        }
1134
1135 11
        $metaData = stream_get_meta_data($handle);
1136 11
        return isset($metaData['seekable']) && $metaData['seekable'] === true;
1137
    }
1138
}
1139