审查视图

vendor/symfony/http-foundation/Response.php 37.5 KB
王智 authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation;

/**
 * Response represents an HTTP response.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Response
{
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;
    const HTTP_PROCESSING = 102;            // RFC2518
    const HTTP_EARLY_HINTS = 103;           // RFC8297
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;
    const HTTP_MULTI_STATUS = 207;          // RFC4918
    const HTTP_ALREADY_REPORTED = 208;      // RFC5842
    const HTTP_IM_USED = 226;               // RFC3229
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_RESERVED = 306;
    const HTTP_TEMPORARY_REDIRECT = 307;
    const HTTP_PERMANENTLY_REDIRECT = 308;  // RFC7238
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;
    const HTTP_I_AM_A_TEAPOT = 418;                                               // RFC2324
    const HTTP_MISDIRECTED_REQUEST = 421;                                         // RFC7540
    const HTTP_UNPROCESSABLE_ENTITY = 422;                                        // RFC4918
    const HTTP_LOCKED = 423;                                                      // RFC4918
    const HTTP_FAILED_DEPENDENCY = 424;                                           // RFC4918
王智 authored
67 68 69 70 71

    /**
     * @deprecated
     */
    const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425;   // RFC2817
王智 authored
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    const HTTP_TOO_EARLY = 425;                                                   // RFC-ietf-httpbis-replay-04
    const HTTP_UPGRADE_REQUIRED = 426;                                            // RFC2817
    const HTTP_PRECONDITION_REQUIRED = 428;                                       // RFC6585
    const HTTP_TOO_MANY_REQUESTS = 429;                                           // RFC6585
    const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;                             // RFC6585
    const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;
    const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;                        // RFC2295
    const HTTP_INSUFFICIENT_STORAGE = 507;                                        // RFC4918
    const HTTP_LOOP_DETECTED = 508;                                               // RFC5842
    const HTTP_NOT_EXTENDED = 510;                                                // RFC2774
    const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;                             // RFC6585

    /**
     * @var ResponseHeaderBag
     */
    public $headers;

    /**
     * @var string
     */
    protected $content;

    /**
     * @var string
     */
    protected $version;

    /**
     * @var int
     */
    protected $statusCode;

    /**
     * @var string
     */
    protected $statusText;

    /**
     * @var string
     */
    protected $charset;

    /**
     * Status codes translation table.
     *
     * The list of codes is complete according to the
     * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry}
     * (last updated 2016-03-01).
     *
     * Unless otherwise noted, the status code is defined in RFC2616.
     *
     * @var array
     */
    public static $statusTexts = [
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',            // RFC2518
        103 => 'Early Hints',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',          // RFC4918
        208 => 'Already Reported',      // RFC5842
        226 => 'IM Used',               // RFC3229
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',    // RFC7238
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Payload Too Large',
        414 => 'URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'I\'m a teapot',                                               // RFC2324
        421 => 'Misdirected Request',                                         // RFC7540
        422 => 'Unprocessable Entity',                                        // RFC4918
        423 => 'Locked',                                                      // RFC4918
        424 => 'Failed Dependency',                                           // RFC4918
        425 => 'Too Early',                                                   // RFC-ietf-httpbis-replay-04
        426 => 'Upgrade Required',                                            // RFC2817
        428 => 'Precondition Required',                                       // RFC6585
        429 => 'Too Many Requests',                                           // RFC6585
        431 => 'Request Header Fields Too Large',                             // RFC6585
        451 => 'Unavailable For Legal Reasons',                               // RFC7725
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',                                     // RFC2295
        507 => 'Insufficient Storage',                                        // RFC4918
        508 => 'Loop Detected',                                               // RFC5842
        510 => 'Not Extended',                                                // RFC2774
        511 => 'Network Authentication Required',                             // RFC6585
    ];

    /**
王智 authored
197 198 199 200
     * @param mixed $content The response content, see setContent()
     * @param int   $status  The response status code
     * @param array $headers An array of response headers
     *
王智 authored
201 202
     * @throws \InvalidArgumentException When the HTTP status code is not valid
     */
王智 authored
203
    public function __construct($content = '', $status = 200, $headers = [])
王智 authored
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    {
        $this->headers = new ResponseHeaderBag($headers);
        $this->setContent($content);
        $this->setStatusCode($status);
        $this->setProtocolVersion('1.0');
    }

    /**
     * Factory method for chainability.
     *
     * Example:
     *
     *     return Response::create($body, 200)
     *         ->setSharedMaxAge(300);
     *
王智 authored
219 220 221
     * @param mixed $content The response content, see setContent()
     * @param int   $status  The response status code
     * @param array $headers An array of response headers
王智 authored
222
     *
王智 authored
223
     * @return static
王智 authored
224
     */
王智 authored
225
    public static function create($content = '', $status = 200, $headers = [])
王智 authored
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    {
        return new static($content, $status, $headers);
    }

    /**
     * Returns the Response as an HTTP string.
     *
     * The string representation of the Response is the same as the
     * one that will be sent to the client only if the prepare() method
     * has been called before.
     *
     * @return string The Response as an HTTP string
     *
     * @see prepare()
     */
    public function __toString()
    {
        return
            sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
            $this->headers."\r\n".
            $this->getContent();
    }

    /**
     * Clones the current Response instance.
     */
    public function __clone()
    {
        $this->headers = clone $this->headers;
    }

    /**
     * Prepares the Response before it is sent to the client.
     *
     * This method tweaks the Response to ensure that it is
     * compliant with RFC 2616. Most of the changes are based on
     * the Request that is "associated" with this Response.
     *
     * @return $this
     */
    public function prepare(Request $request)
    {
        $headers = $this->headers;

        if ($this->isInformational() || $this->isEmpty()) {
            $this->setContent(null);
            $headers->remove('Content-Type');
            $headers->remove('Content-Length');
        } else {
            // Content-type based on the Request
            if (!$headers->has('Content-Type')) {
王智 authored
277
                $format = $request->getRequestFormat();
王智 authored
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
                if (null !== $format && $mimeType = $request->getMimeType($format)) {
                    $headers->set('Content-Type', $mimeType);
                }
            }

            // Fix Content-Type
            $charset = $this->charset ?: 'UTF-8';
            if (!$headers->has('Content-Type')) {
                $headers->set('Content-Type', 'text/html; charset='.$charset);
            } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
                // add the charset
                $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
            }

            // Fix Content-Length
            if ($headers->has('Transfer-Encoding')) {
                $headers->remove('Content-Length');
            }

            if ($request->isMethod('HEAD')) {
                // cf. RFC2616 14.13
                $length = $headers->get('Content-Length');
                $this->setContent(null);
                if ($length) {
                    $headers->set('Content-Length', $length);
                }
            }
        }

        // Fix protocol
        if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
            $this->setProtocolVersion('1.1');
        }

        // Check if we need to send extra expire info headers
        if ('1.0' == $this->getProtocolVersion() && false !== strpos($headers->get('Cache-Control'), 'no-cache')) {
            $headers->set('pragma', 'no-cache');
            $headers->set('expires', -1);
        }

        $this->ensureIEOverSSLCompatibility($request);

        return $this;
    }

    /**
     * Sends HTTP headers.
     *
     * @return $this
     */
    public function sendHeaders()
    {
        // headers have already been sent by the developer
        if (headers_sent()) {
            return $this;
        }

        // headers
        foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
            $replace = 0 === strcasecmp($name, 'Content-Type');
            foreach ($values as $value) {
                header($name.': '.$value, $replace, $this->statusCode);
            }
        }

        // cookies
        foreach ($this->headers->getCookies() as $cookie) {
            header('Set-Cookie: '.$cookie, false, $this->statusCode);
        }

        // status
        header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);

        return $this;
    }

    /**
     * Sends content for the current web response.
     *
     * @return $this
     */
    public function sendContent()
    {
        echo $this->content;

        return $this;
    }

    /**
     * Sends HTTP headers and content.
     *
     * @return $this
     */
    public function send()
    {
        $this->sendHeaders();
        $this->sendContent();

        if (\function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
            static::closeOutputBuffers(0, true);
        }

        return $this;
    }

    /**
     * Sets the response content.
     *
王智 authored
388 389 390 391
     * Valid types are strings, numbers, null, and objects that implement a __toString() method.
     *
     * @param mixed $content Content that can be cast to string
     *
王智 authored
392 393 394 395
     * @return $this
     *
     * @throws \UnexpectedValueException
     */
王智 authored
396
    public function setContent($content)
王智 authored
397
    {
王智 authored
398 399 400 401 402
        if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable([$content, '__toString'])) {
            throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content)));
        }

        $this->content = (string) $content;
王智 authored
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

        return $this;
    }

    /**
     * Gets the current response content.
     *
     * @return string|false
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Sets the HTTP protocol version (1.0 or 1.1).
     *
王智 authored
420 421
     * @param string $version The HTTP protocol version
     *
王智 authored
422 423
     * @return $this
     *
王智 authored
424
     * @final since version 3.2
王智 authored
425
     */
王智 authored
426
    public function setProtocolVersion($version)
王智 authored
427 428 429 430 431 432 433 434 435
    {
        $this->version = $version;

        return $this;
    }

    /**
     * Gets the HTTP protocol version.
     *
王智 authored
436 437 438
     * @return string The HTTP protocol version
     *
     * @final since version 3.2
王智 authored
439
     */
王智 authored
440
    public function getProtocolVersion()
王智 authored
441 442 443 444 445 446 447 448 449 450
    {
        return $this->version;
    }

    /**
     * Sets the response status code.
     *
     * If the status text is null it will be automatically populated for the known
     * status codes and left empty otherwise.
     *
王智 authored
451 452 453
     * @param int   $code HTTP status code
     * @param mixed $text HTTP status text
     *
王智 authored
454 455 456 457
     * @return $this
     *
     * @throws \InvalidArgumentException When the HTTP status code is not valid
     *
王智 authored
458
     * @final since version 3.2
王智 authored
459
     */
王智 authored
460
    public function setStatusCode($code, $text = null)
王智 authored
461
    {
王智 authored
462
        $this->statusCode = $code = (int) $code;
王智 authored
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
        if ($this->isInvalid()) {
            throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
        }

        if (null === $text) {
            $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';

            return $this;
        }

        if (false === $text) {
            $this->statusText = '';

            return $this;
        }

        $this->statusText = $text;

        return $this;
    }

    /**
     * Retrieves the status code for the current web response.
     *
王智 authored
487 488 489
     * @return int Status code
     *
     * @final since version 3.2
王智 authored
490
     */
王智 authored
491
    public function getStatusCode()
王智 authored
492 493 494 495 496 497 498
    {
        return $this->statusCode;
    }

    /**
     * Sets the response charset.
     *
王智 authored
499 500
     * @param string $charset Character set
     *
王智 authored
501 502
     * @return $this
     *
王智 authored
503
     * @final since version 3.2
王智 authored
504
     */
王智 authored
505
    public function setCharset($charset)
王智 authored
506 507 508 509 510 511 512 513 514
    {
        $this->charset = $charset;

        return $this;
    }

    /**
     * Retrieves the response charset.
     *
王智 authored
515 516 517
     * @return string Character set
     *
     * @final since version 3.2
王智 authored
518
     */
王智 authored
519
    public function getCharset()
王智 authored
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    {
        return $this->charset;
    }

    /**
     * Returns true if the response may safely be kept in a shared (surrogate) cache.
     *
     * Responses marked "private" with an explicit Cache-Control directive are
     * considered uncacheable.
     *
     * Responses with neither a freshness lifetime (Expires, max-age) nor cache
     * validator (Last-Modified, ETag) are considered uncacheable because there is
     * no way to tell when or how to remove them from the cache.
     *
     * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
     * for example "status codes that are defined as cacheable by default [...]
     * can be reused by a cache with heuristic expiration unless otherwise indicated"
     * (https://tools.ietf.org/html/rfc7231#section-6.1)
     *
王智 authored
539 540 541
     * @return bool true if the response is worth caching, false otherwise
     *
     * @final since version 3.3
王智 authored
542
     */
王智 authored
543
    public function isCacheable()
王智 authored
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    {
        if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410])) {
            return false;
        }

        if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
            return false;
        }

        return $this->isValidateable() || $this->isFresh();
    }

    /**
     * Returns true if the response is "fresh".
     *
     * Fresh responses may be served from cache without any interaction with the
     * origin. A response is considered fresh when it includes a Cache-Control/max-age
     * indicator or Expires header and the calculated age is less than the freshness lifetime.
     *
王智 authored
563 564 565
     * @return bool true if the response is fresh, false otherwise
     *
     * @final since version 3.3
王智 authored
566
     */
王智 authored
567
    public function isFresh()
王智 authored
568 569 570 571 572 573 574 575
    {
        return $this->getTtl() > 0;
    }

    /**
     * Returns true if the response includes headers that can be used to validate
     * the response with the origin server using a conditional GET request.
     *
王智 authored
576 577 578
     * @return bool true if the response is validateable, false otherwise
     *
     * @final since version 3.3
王智 authored
579
     */
王智 authored
580
    public function isValidateable()
王智 authored
581 582 583 584 585 586 587 588 589 590 591
    {
        return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
    }

    /**
     * Marks the response as "private".
     *
     * It makes the response ineligible for serving other clients.
     *
     * @return $this
     *
王智 authored
592
     * @final since version 3.2
王智 authored
593
     */
王智 authored
594
    public function setPrivate()
王智 authored
595 596 597 598 599 600 601 602 603 604 605 606 607 608
    {
        $this->headers->removeCacheControlDirective('public');
        $this->headers->addCacheControlDirective('private');

        return $this;
    }

    /**
     * Marks the response as "public".
     *
     * It makes the response eligible for serving other clients.
     *
     * @return $this
     *
王智 authored
609
     * @final since version 3.2
王智 authored
610
     */
王智 authored
611
    public function setPublic()
王智 authored
612 613 614 615 616 617 618 619 620 621
    {
        $this->headers->addCacheControlDirective('public');
        $this->headers->removeCacheControlDirective('private');

        return $this;
    }

    /**
     * Marks the response as "immutable".
     *
王智 authored
622 623
     * @param bool $immutable enables or disables the immutable directive
     *
王智 authored
624 625 626 627
     * @return $this
     *
     * @final
     */
王智 authored
628
    public function setImmutable($immutable = true)
王智 authored
629 630 631 632 633 634 635 636 637 638 639 640 641
    {
        if ($immutable) {
            $this->headers->addCacheControlDirective('immutable');
        } else {
            $this->headers->removeCacheControlDirective('immutable');
        }

        return $this;
    }

    /**
     * Returns true if the response is marked as "immutable".
     *
王智 authored
642 643
     * @return bool returns true if the response is marked as "immutable"; otherwise false
     *
王智 authored
644 645
     * @final
     */
王智 authored
646
    public function isImmutable()
王智 authored
647 648 649 650 651 652 653 654 655 656 657 658
    {
        return $this->headers->hasCacheControlDirective('immutable');
    }

    /**
     * Returns true if the response must be revalidated by shared caches once it has become stale.
     *
     * This method indicates that the response must not be served stale by a
     * cache in any circumstance without first revalidating with the origin.
     * When present, the TTL of the response should not be overridden to be
     * greater than the value provided by the origin.
     *
王智 authored
659 660 661
     * @return bool true if the response must be revalidated by a cache, false otherwise
     *
     * @final since version 3.3
王智 authored
662
     */
王智 authored
663
    public function mustRevalidate()
王智 authored
664 665 666 667 668 669 670
    {
        return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
    }

    /**
     * Returns the Date header as a DateTime instance.
     *
王智 authored
671 672
     * @return \DateTime A \DateTime instance
     *
王智 authored
673 674
     * @throws \RuntimeException When the header is not parseable
     *
王智 authored
675
     * @final since version 3.2
王智 authored
676
     */
王智 authored
677
    public function getDate()
王智 authored
678 679 680 681 682 683 684 685 686
    {
        return $this->headers->getDate('Date');
    }

    /**
     * Sets the Date header.
     *
     * @return $this
     *
王智 authored
687
     * @final since version 3.2
王智 authored
688
     */
王智 authored
689
    public function setDate(\DateTime $date)
王智 authored
690
    {
王智 authored
691
        $date->setTimezone(new \DateTimeZone('UTC'));
王智 authored
692 693 694 695 696 697
        $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');

        return $this;
    }

    /**
王智 authored
698
     * Returns the age of the response.
王智 authored
699
     *
王智 authored
700 701 702
     * @return int The age of the response in seconds
     *
     * @final since version 3.2
王智 authored
703
     */
王智 authored
704
    public function getAge()
王智 authored
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    {
        if (null !== $age = $this->headers->get('Age')) {
            return (int) $age;
        }

        return max(time() - (int) $this->getDate()->format('U'), 0);
    }

    /**
     * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
     *
     * @return $this
     */
    public function expire()
    {
        if ($this->isFresh()) {
            $this->headers->set('Age', $this->getMaxAge());
            $this->headers->remove('Expires');
        }

        return $this;
    }

    /**
     * Returns the value of the Expires header as a DateTime instance.
     *
王智 authored
731 732 733
     * @return \DateTime|null A DateTime instance or null if the header does not exist
     *
     * @final since version 3.2
王智 authored
734
     */
王智 authored
735
    public function getExpires()
王智 authored
736 737 738 739 740
    {
        try {
            return $this->headers->getDate('Expires');
        } catch (\RuntimeException $e) {
            // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
王智 authored
741
            return \DateTime::createFromFormat(\DATE_RFC2822, 'Sat, 01 Jan 00 00:00:00 +0000');
王智 authored
742 743 744 745 746 747 748 749
        }
    }

    /**
     * Sets the Expires HTTP header with a DateTime instance.
     *
     * Passing null as value will remove the header.
     *
王智 authored
750 751
     * @param \DateTime|null $date A \DateTime instance or null to remove the header
     *
王智 authored
752 753
     * @return $this
     *
王智 authored
754
     * @final since version 3.2
王智 authored
755
     */
王智 authored
756
    public function setExpires(\DateTime $date = null)
王智 authored
757 758 759
    {
        if (null === $date) {
            $this->headers->remove('Expires');
王智 authored
760 761 762 763
        } else {
            $date = clone $date;
            $date->setTimezone(new \DateTimeZone('UTC'));
            $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
王智 authored
764 765
        }
王智 authored
766 767 768 769 770 771 772 773 774 775
        return $this;
    }

    /**
     * Returns the number of seconds after the time specified in the response's Date
     * header when the response should no longer be considered fresh.
     *
     * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
     * back on an expires header. It returns null when no maximum age can be established.
     *
王智 authored
776 777 778
     * @return int|null Number of seconds
     *
     * @final since version 3.2
王智 authored
779
     */
王智 authored
780
    public function getMaxAge()
王智 authored
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    {
        if ($this->headers->hasCacheControlDirective('s-maxage')) {
            return (int) $this->headers->getCacheControlDirective('s-maxage');
        }

        if ($this->headers->hasCacheControlDirective('max-age')) {
            return (int) $this->headers->getCacheControlDirective('max-age');
        }

        if (null !== $this->getExpires()) {
            return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U');
        }

        return null;
    }

    /**
     * Sets the number of seconds after which the response should no longer be considered fresh.
     *
     * This methods sets the Cache-Control max-age directive.
     *
王智 authored
802 803
     * @param int $value Number of seconds
     *
王智 authored
804 805
     * @return $this
     *
王智 authored
806
     * @final since version 3.2
王智 authored
807
     */
王智 authored
808
    public function setMaxAge($value)
王智 authored
809 810 811 812 813 814 815 816 817 818 819
    {
        $this->headers->addCacheControlDirective('max-age', $value);

        return $this;
    }

    /**
     * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
     *
     * This methods sets the Cache-Control s-maxage directive.
     *
王智 authored
820 821
     * @param int $value Number of seconds
     *
王智 authored
822 823
     * @return $this
     *
王智 authored
824
     * @final since version 3.2
王智 authored
825
     */
王智 authored
826
    public function setSharedMaxAge($value)
王智 authored
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    {
        $this->setPublic();
        $this->headers->addCacheControlDirective('s-maxage', $value);

        return $this;
    }

    /**
     * Returns the response's time-to-live in seconds.
     *
     * It returns null when no freshness information is present in the response.
     *
     * When the responses TTL is <= 0, the response may not be served from cache without first
     * revalidating with the origin.
     *
王智 authored
842 843 844
     * @return int|null The TTL in seconds
     *
     * @final since version 3.2
王智 authored
845
     */
王智 authored
846
    public function getTtl()
王智 authored
847
    {
王智 authored
848 849 850
        if (null !== $maxAge = $this->getMaxAge()) {
            return $maxAge - $this->getAge();
        }
王智 authored
851
王智 authored
852
        return null;
王智 authored
853 854 855
    }

    /**
王智 authored
856
     * Sets the response's time-to-live for shared caches.
王智 authored
857 858 859
     *
     * This method adjusts the Cache-Control/s-maxage directive.
     *
王智 authored
860 861
     * @param int $seconds Number of seconds
     *
王智 authored
862 863
     * @return $this
     *
王智 authored
864
     * @final since version 3.2
王智 authored
865
     */
王智 authored
866
    public function setTtl($seconds)
王智 authored
867 868 869 870 871 872 873
    {
        $this->setSharedMaxAge($this->getAge() + $seconds);

        return $this;
    }

    /**
王智 authored
874
     * Sets the response's time-to-live for private/client caches.
王智 authored
875 876 877
     *
     * This method adjusts the Cache-Control/max-age directive.
     *
王智 authored
878 879
     * @param int $seconds Number of seconds
     *
王智 authored
880 881
     * @return $this
     *
王智 authored
882
     * @final since version 3.2
王智 authored
883
     */
王智 authored
884
    public function setClientTtl($seconds)
王智 authored
885 886 887 888 889 890 891 892 893
    {
        $this->setMaxAge($this->getAge() + $seconds);

        return $this;
    }

    /**
     * Returns the Last-Modified HTTP header as a DateTime instance.
     *
王智 authored
894 895
     * @return \DateTime|null A DateTime instance or null if the header does not exist
     *
王智 authored
896 897
     * @throws \RuntimeException When the HTTP header is not parseable
     *
王智 authored
898
     * @final since version 3.2
王智 authored
899
     */
王智 authored
900
    public function getLastModified()
王智 authored
901 902 903 904 905 906 907 908 909
    {
        return $this->headers->getDate('Last-Modified');
    }

    /**
     * Sets the Last-Modified HTTP header with a DateTime instance.
     *
     * Passing null as value will remove the header.
     *
王智 authored
910 911
     * @param \DateTime|null $date A \DateTime instance or null to remove the header
     *
王智 authored
912 913
     * @return $this
     *
王智 authored
914
     * @final since version 3.2
王智 authored
915
     */
王智 authored
916
    public function setLastModified(\DateTime $date = null)
王智 authored
917 918 919
    {
        if (null === $date) {
            $this->headers->remove('Last-Modified');
王智 authored
920 921 922 923
        } else {
            $date = clone $date;
            $date->setTimezone(new \DateTimeZone('UTC'));
            $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
王智 authored
924 925 926 927 928 929 930 931
        }

        return $this;
    }

    /**
     * Returns the literal value of the ETag HTTP header.
     *
王智 authored
932 933 934
     * @return string|null The ETag HTTP header or null if it does not exist
     *
     * @final since version 3.2
王智 authored
935
     */
王智 authored
936
    public function getEtag()
王智 authored
937 938 939 940 941 942 943 944 945 946 947 948
    {
        return $this->headers->get('ETag');
    }

    /**
     * Sets the ETag value.
     *
     * @param string|null $etag The ETag unique identifier or null to remove the header
     * @param bool        $weak Whether you want a weak ETag or not
     *
     * @return $this
     *
王智 authored
949
     * @final since version 3.2
王智 authored
950
     */
王智 authored
951
    public function setEtag($etag = null, $weak = false)
王智 authored
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
    {
        if (null === $etag) {
            $this->headers->remove('Etag');
        } else {
            if (0 !== strpos($etag, '"')) {
                $etag = '"'.$etag.'"';
            }

            $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
        }

        return $this;
    }

    /**
     * Sets the response's cache headers (validation and/or expiration).
     *
王智 authored
969 970 971
     * Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.
     *
     * @param array $options An array of cache options
王智 authored
972
     *
王智 authored
973 974 975 976
     * @return $this
     *
     * @throws \InvalidArgumentException
     *
王智 authored
977
     * @final since version 3.3
王智 authored
978
     */
王智 authored
979
    public function setCache(array $options)
王智 authored
980
    {
王智 authored
981
        if ($diff = array_diff(array_keys($options), ['etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'])) {
王智 authored
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
            throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
        }

        if (isset($options['etag'])) {
            $this->setEtag($options['etag']);
        }

        if (isset($options['last_modified'])) {
            $this->setLastModified($options['last_modified']);
        }

        if (isset($options['max_age'])) {
            $this->setMaxAge($options['max_age']);
        }

        if (isset($options['s_maxage'])) {
            $this->setSharedMaxAge($options['s_maxage']);
        }

        if (isset($options['public'])) {
            if ($options['public']) {
                $this->setPublic();
            } else {
                $this->setPrivate();
            }
        }

        if (isset($options['private'])) {
            if ($options['private']) {
                $this->setPrivate();
            } else {
                $this->setPublic();
            }
        }
王智 authored
1017 1018 1019 1020
        if (isset($options['immutable'])) {
            $this->setImmutable((bool) $options['immutable']);
        }
王智 authored
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        return $this;
    }

    /**
     * Modifies the response so that it conforms to the rules defined for a 304 status code.
     *
     * This sets the status, removes the body, and discards any headers
     * that MUST NOT be included in 304 responses.
     *
     * @return $this
     *
     * @see https://tools.ietf.org/html/rfc2616#section-10.3.5
     *
王智 authored
1034
     * @final since version 3.3
王智 authored
1035
     */
王智 authored
1036
    public function setNotModified()
王智 authored
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    {
        $this->setStatusCode(304);
        $this->setContent(null);

        // remove headers that MUST NOT be included with 304 Not Modified responses
        foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) {
            $this->headers->remove($header);
        }

        return $this;
    }

    /**
     * Returns true if the response includes a Vary header.
     *
王智 authored
1052 1053 1054
     * @return bool true if the response includes a Vary header, false otherwise
     *
     * @final since version 3.2
王智 authored
1055
     */
王智 authored
1056
    public function hasVary()
王智 authored
1057 1058 1059 1060 1061 1062 1063
    {
        return null !== $this->headers->get('Vary');
    }

    /**
     * Returns an array of header names given in the Vary header.
     *
王智 authored
1064 1065 1066
     * @return array An array of Vary names
     *
     * @final since version 3.2
王智 authored
1067
     */
王智 authored
1068
    public function getVary()
王智 authored
1069
    {
王智 authored
1070
        if (!$vary = $this->headers->get('Vary', null, false)) {
王智 authored
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            return [];
        }

        $ret = [];
        foreach ($vary as $item) {
            $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
        }

        return $ret;
    }

    /**
     * Sets the Vary header.
     *
     * @param string|array $headers
     * @param bool         $replace Whether to replace the actual value or not (true by default)
     *
     * @return $this
     *
王智 authored
1090
     * @final since version 3.2
王智 authored
1091
     */
王智 authored
1092
    public function setVary($headers, $replace = true)
王智 authored
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    {
        $this->headers->set('Vary', $headers, $replace);

        return $this;
    }

    /**
     * Determines if the Response validators (ETag, Last-Modified) match
     * a conditional value specified in the Request.
     *
     * If the Response is not modified, it sets the status code to 304 and
     * removes the actual content by calling the setNotModified() method.
     *
     * @return bool true if the Response validators match the Request, false otherwise
     *
王智 authored
1108
     * @final since version 3.3
王智 authored
1109
     */
王智 authored
1110
    public function isNotModified(Request $request)
王智 authored
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    {
        if (!$request->isMethodCacheable()) {
            return false;
        }

        $notModified = false;
        $lastModified = $this->headers->get('Last-Modified');
        $modifiedSince = $request->headers->get('If-Modified-Since');

        if ($etags = $request->getETags()) {
            $notModified = \in_array($this->getEtag(), $etags) || \in_array('*', $etags);
        }

        if ($modifiedSince && $lastModified) {
            $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
        }

        if ($notModified) {
            $this->setNotModified();
        }

        return $notModified;
    }

    /**
     * Is response invalid?
     *
王智 authored
1138 1139
     * @return bool
     *
王智 authored
1140 1141
     * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
     *
王智 authored
1142
     * @final since version 3.2
王智 authored
1143
     */
王智 authored
1144
    public function isInvalid()
王智 authored
1145 1146 1147 1148 1149 1150 1151
    {
        return $this->statusCode < 100 || $this->statusCode >= 600;
    }

    /**
     * Is response informative?
     *
王智 authored
1152 1153 1154
     * @return bool
     *
     * @final since version 3.3
王智 authored
1155
     */
王智 authored
1156
    public function isInformational()
王智 authored
1157 1158 1159 1160 1161 1162 1163
    {
        return $this->statusCode >= 100 && $this->statusCode < 200;
    }

    /**
     * Is response successful?
     *
王智 authored
1164 1165 1166
     * @return bool
     *
     * @final since version 3.2
王智 authored
1167
     */
王智 authored
1168
    public function isSuccessful()
王智 authored
1169 1170 1171 1172 1173 1174 1175
    {
        return $this->statusCode >= 200 && $this->statusCode < 300;
    }

    /**
     * Is the response a redirect?
     *
王智 authored
1176 1177 1178
     * @return bool
     *
     * @final since version 3.2
王智 authored
1179
     */
王智 authored
1180
    public function isRedirection()
王智 authored
1181 1182 1183 1184 1185 1186 1187
    {
        return $this->statusCode >= 300 && $this->statusCode < 400;
    }

    /**
     * Is there a client error?
     *
王智 authored
1188 1189 1190
     * @return bool
     *
     * @final since version 3.2
王智 authored
1191
     */
王智 authored
1192
    public function isClientError()
王智 authored
1193 1194 1195 1196 1197 1198 1199
    {
        return $this->statusCode >= 400 && $this->statusCode < 500;
    }

    /**
     * Was there a server side error?
     *
王智 authored
1200 1201 1202
     * @return bool
     *
     * @final since version 3.3
王智 authored
1203
     */
王智 authored
1204
    public function isServerError()
王智 authored
1205 1206 1207 1208 1209 1210 1211
    {
        return $this->statusCode >= 500 && $this->statusCode < 600;
    }

    /**
     * Is the response OK?
     *
王智 authored
1212 1213 1214
     * @return bool
     *
     * @final since version 3.2
王智 authored
1215
     */
王智 authored
1216
    public function isOk()
王智 authored
1217 1218 1219 1220 1221 1222 1223
    {
        return 200 === $this->statusCode;
    }

    /**
     * Is the response forbidden?
     *
王智 authored
1224 1225 1226
     * @return bool
     *
     * @final since version 3.2
王智 authored
1227
     */
王智 authored
1228
    public function isForbidden()
王智 authored
1229 1230 1231 1232 1233 1234 1235
    {
        return 403 === $this->statusCode;
    }

    /**
     * Is the response a not found error?
     *
王智 authored
1236 1237 1238
     * @return bool
     *
     * @final since version 3.2
王智 authored
1239
     */
王智 authored
1240
    public function isNotFound()
王智 authored
1241 1242 1243 1244 1245 1246 1247
    {
        return 404 === $this->statusCode;
    }

    /**
     * Is the response a redirect of some form?
     *
王智 authored
1248 1249 1250 1251 1252
     * @param string $location
     *
     * @return bool
     *
     * @final since version 3.2
王智 authored
1253
     */
王智 authored
1254
    public function isRedirect($location = null)
王智 authored
1255 1256 1257 1258 1259 1260 1261
    {
        return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location'));
    }

    /**
     * Is the response empty?
     *
王智 authored
1262 1263 1264
     * @return bool
     *
     * @final since version 3.2
王智 authored
1265
     */
王智 authored
1266
    public function isEmpty()
王智 authored
1267 1268 1269 1270 1271 1272 1273 1274 1275
    {
        return \in_array($this->statusCode, [204, 304]);
    }

    /**
     * Cleans or flushes output buffers up to target level.
     *
     * Resulting level can be greater than target level if a non-removable buffer has been encountered.
     *
王智 authored
1276 1277 1278 1279
     * @param int  $targetLevel The target output buffering level
     * @param bool $flush       Whether to flush or clean the buffers
     *
     * @final since version 3.3
王智 authored
1280
     */
王智 authored
1281
    public static function closeOutputBuffers($targetLevel, $flush)
王智 authored
1282 1283 1284
    {
        $status = ob_get_status(true);
        $level = \count($status);
王智 authored
1285 1286
        // PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
        $flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE) : -1;
王智 authored
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301

        while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
            if ($flush) {
                ob_end_flush();
            } else {
                ob_end_clean();
            }
        }
    }

    /**
     * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
     *
     * @see http://support.microsoft.com/kb/323308
     *
王智 authored
1302
     * @final since version 3.3
王智 authored
1303
     */
王智 authored
1304
    protected function ensureIEOverSSLCompatibility(Request $request)
王智 authored
1305 1306 1307 1308 1309 1310 1311 1312
    {
        if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
            if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
                $this->headers->remove('Cache-Control');
            }
        }
    }
}