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 67 68 69 70 71 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 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 277 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\HTTP;
use ICanBoogie\Accessor\AccessorTrait;
/**
* A response to a HTTP request.
*
* @property Status $status
* @property mixed $body The body of the response.
*
* @property int $ttl Adjusts the `s-maxage` part of the `Cache-Control` header field definition according to the `Age` header field definition.
* @property int $age Shortcut to the `Age` header field definition.
* @property Headers\CacheControl $cache_control Shortcut to the `Cache-Control` header field definition.
* @property int $content_length Shortcut to the `Content-Length` header field definition.
* @property Headers\ContentType $content_type Shortcut to the `Content-Type` header field definition.
* @property Headers\Date $date Shortcut to the `Date` header field definition.
* @property string $etag Shortcut to the `ETag` header field definition.
* @property Headers\Date $expires Shortcut to the `Expires` header field definition.
* @property Headers\Date $last_modified Shortcut to the `Last-Modified` header field definition.
* @property string $location Shortcut to the `Location` header field definition.
*
* @property-read boolean $is_cacheable {@link get_is_cacheable()}
* @property-read boolean $is_fresh {@link get_is_fresh()}
* @property-read boolean $is_private {@link get_is_private()}
* @property-read boolean $is_validateable {@link get_is_validateable()}
*
* @see http://tools.ietf.org/html/rfc2616
*/
class Response implements ResponseStatus
{
use AccessorTrait;
/**
* Response headers.
*
* @var Headers
*/
public $headers;
/**
* The HTTP protocol version (1.0 or 1.1), defaults to '1.0'
*
* @var string
*/
public $version = '1.0';
/**
* Initializes the {@link $body}, {@link $header}, {@link $date} and {@link $status}
* properties.
*
* @param mixed $body The body of the response.
* @param int|Status $status The status code of the response.
* @param Headers|array $headers The initial header fields of the response.
*/
public function __construct($body = null, $status = self::STATUS_OK, $headers = [])
{
if (is_array($headers))
{
$headers = new Headers($headers);
}
else if (!$headers instanceof Headers)
{
throw new \InvalidArgumentException("\$headers must be an array or a ICanBoogie\\HTTP\\Headers instance. Given: " . gettype($headers));
}
$this->headers = $headers;
if ($this->date->is_empty)
{
$this->date = 'now';
}
$this->set_status($status);
if ($body !== null)
{
$this->set_body($body);
}
}
/**
* Clones the {@link $headers} and {@link $status} properties.
*/
public function __clone()
{
$this->headers = clone $this->headers;
$this->status = clone $this->status;
}
/**
* Renders the response as an HTTP string.
*
* @return string
*/
public function __toString()
{
try
{
$header = clone $this->headers;
$body = $this->body;
$this->finalize($header, $body);
ob_start();
$this->send_body($body);
$body = ob_get_clean();
return "HTTP/{$this->version} {$this->status}\r\n"
. $header
. "\r\n"
. $body;
}
catch (\Exception $e)
{
return $e->getMessage();
}
}
/**
* Issues the HTTP response.
*
* {@link finalize()} is invoked to finalize the headers (a cloned actually)
* and the body. {@link send_headers} is invoked to send the headers and {@link send_body()}
*is invoked to send the body, if the body is not `null`.
*
* The body is not send in the following instances:
*
* - The finalized body is `null`.
* - The status is not ok.
*/
public function __invoke()
{
$headers = clone $this->headers;
$body = $this->body;
$this->finalize($headers, $body);
$this->send_headers($headers);
if ($body === null)
{
return;
}
$this->send_body($body);
}
/**
* Finalize the body.
*
* Subclasses might want to override this method if they wish to alter the header or the body
* before the response is sent or transformed into a string.
*
* @param Headers $headers Reference to the final header.
* @param mixed $body Reference to the final body.
*/
protected function finalize(Headers &$headers, &$body)
{
if ($body instanceof \Closure || !method_exists($body, '__toString'))
{
return;
}
$body = (string) $body;
}
/**
* Sends response headers.
*
* @param Headers $headers
*
* @return bool `true` is the headers were sent, `false` otherwise.
*/
// @codeCoverageIgnoreStart
protected function send_headers(Headers $headers)
{
if (headers_sent($file, $line))
{
trigger_error(\ICanBoogie\format("Cannot modify header information because it was already sent. Output started at !at.", [
'at' => $file . ':' . $line
]));
return false;
}
header_remove('Pragma');
header_remove('X-Powered-By');
header("HTTP/{$this->version} {$this->status}");
$headers();
return true;
}
// @codeCoverageIgnoreEnd
/**
* Sends response body.
*
* @param mixed $body
*/
protected function send_body($body)
{
if ($body instanceof \Closure)
{
$body($this);
return;
}
echo $body;
}
/**
* Status of the HTTP response.
*
* @var Status
*/
private $status;
/**
* Sets response status code and optionally status message.
*
* @param int|Status $status HTTP status code or HTTP status code and HTTP status message.
*/
protected function set_status($status)
{
$this->status = Status::from($status);
}
/**
* Returns the response status.
*
* @return Status
*/
protected function get_status()
{
return $this->status;
}
/**
* The response body.
*
* @var mixed
*
* @see set_body(), get_body()
*/
private $body;
/**
* Sets the response body.
*
* The body can be any data type that can be converted into a string. This includes numeric
* and objects implementing the {@link __toString()} method.
*
* @param string|\Closure|null $body
*
* @throws \UnexpectedValueException when the body cannot be converted to a string.
*/
protected function set_body($body)
{
$this->assert_body_is_valid($body);
$this->body = $body;
}
/**
* Asserts that the a body is valid.
*
* @param $body
*
* @throws \UnexpectedValueException if the specified body doesn't meet the requirements.
*/
protected function assert_body_is_valid($body)
{
if ($body === null
|| $body instanceof \Closure
|| is_numeric($body)
|| is_string($body)
|| (is_object($body) && method_exists($body, '__toString')))
{
return;
}
throw new \UnexpectedValueException(\ICanBoogie\format('The Response body must be a string, an object implementing the __toString() method or be callable, %type given. !value', [
'type' => gettype($body),
'value' => $body
]));
}
/**
* Returns the response body.
*
* @return string
*/
protected function get_body()
{
return $this->body;
}
/**
* Sets the value of the `Location` header field.
*
* @param string|null $url
*/
protected function set_location($url)
{
if ($url !== null && !$url)
{
throw new \InvalidArgumentException('Cannot redirect to an empty URL.');
}
$this->headers['Location'] = $url;
}
/**
* Returns the value of the `Location` header field.
*
* @return string
*/
protected function get_location()
{
return $this->headers['Location'];
}
/**
* Sets the value of the `Content-Type` header field.
*
* @param string $content_type
*/
protected function set_content_type($content_type)
{
$this->headers['Content-Type'] = $content_type;
}
/**
* Returns the value of the `Content-Type` header field.
*
* @return Headers\ContentType
*/
protected function get_content_type()
{
return $this->headers['Content-Type'];
}
/**
* Sets the value of the `Content-Length` header field.
*
* @param int $length
*/
protected function set_content_length($length)
{
$this->headers['Content-Length'] = $length;
}
/**
* Returns the value of the `Content-Length` header field.
*
* @return int
*/
protected function get_content_length()
{
return $this->headers['Content-Length'];
}
/**
* Sets the value of the `Date` header field.
*
* @param mixed $time
*/
protected function set_date($time)
{
$this->headers['Date'] = $time;
}
/**
* Returns the value of the `Date` header field.
*
* @return Headers\Date
*/
protected function get_date()
{
return $this->headers['Date'];
}
/**
* Sets the value of the `Age` header field.
*
* @param int $age
*/
protected function set_age($age)
{
$this->headers['Age'] = $age;
}
/**
* Returns the age of the response.
*
* @return int
*/
protected function get_age()
{
$age = $this->headers['Age'];
if ($age)
{
return $age;
}
if (!$this->date->is_empty)
{
return max(0, time() - $this->date->utc->timestamp);
}
return null;
}
/**
* Sets the value of the `Last-Modified` header field.
*
* @param mixed $time
*/
protected function set_last_modified($time)
{
$this->headers['Last-Modified'] = $time;
}
/**
* Returns the value of the `Last-Modified` header field.
*
* @return Headers\Date
*/
protected function get_last_modified()
{
return $this->headers['Last-Modified'];
}
/**
* Sets the value of the `Expires` header field.
*
* The method also calls the {@link session_cache_expire()} function.
*
* @param mixed $time
*/
protected function set_expires($time)
{
$this->headers['Expires'] = $time;
}
/**
* Returns the value of the `Expires` header field.
*
* @return Headers\Date
*/
protected function get_expires()
{
return $this->headers['Expires'];
}
/**
* Sets the value of the `ETag` header field.
*
* @param string $value
*/
protected function set_etag($value)
{
$this->headers['ETag'] = $value;
}
/**
* Returns the value of the `ETag` header field.
*
* @return string
*/
protected function get_etag()
{
return $this->headers['ETag'];
}
/**
* Sets the directives of the `Cache-Control` header field.
*
* @param string $cache_directives
*/
protected function set_cache_control($cache_directives)
{
$this->headers['Cache-Control'] = $cache_directives;
}
/**
* Returns the `Cache-Control` header field.
*
* @return Headers\CacheControl
*/
protected function get_cache_control()
{
return $this->headers['Cache-Control'];
}
/**
* Sets the response's time-to-live for shared caches.
*
* This method adjusts the Cache-Control/s-maxage directive.
*
* @param int $seconds The number of seconds.
*/
protected function set_ttl($seconds)
{
$this->cache_control->s_maxage = $this->age + $seconds;
}
/**
* Returns the response's time-to-live in seconds.
*
* When the responses TTL is <= 0, the response may not be served from cache without first
* re-validating with the origin.
*
* @return int|null The number of seconds to live, or `null` is no freshness information
* is present.
*/
protected function get_ttl()
{
$max_age = $this->cache_control->max_age;
if ($max_age)
{
return $max_age - $this->age;
}
return null;
}
/**
* Checks that the response includes header fields that can be used to validate the response
* with the origin server using a conditional GET request.
*
* @return boolean
*/
protected function get_is_validateable()
{
return !$this->headers['Last-Modified']->is_empty || $this->headers['ETag'];
}
/**
* Checks that the response is worth caching under any circumstance.
*
* Responses marked _private_ with an explicit `Cache-Control` directive are considered
* not cacheable.
*
* Responses with neither a freshness lifetime (Expires, max-age) nor cache validator
* (`Last-Modified`, `ETag`) are considered not cacheable.
*
* @return boolean
*/
protected function get_is_cacheable()
{
if (!$this->status->is_cacheable || $this->cache_control->no_store || $this->cache_control->cacheable == 'private')
{
return false;
}
return $this->is_validateable || $this->is_fresh;
}
/**
* Checks if the response is fresh.
*
* @return boolean
*/
protected function get_is_fresh()
{
return $this->ttl > 0;
}
}