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 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 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 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
<?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;
use ICanBoogie\Prototype\MethodNotDefined;
/**
* An HTTP request.
*
* <pre>
* <?php
*
* use ICanBoogie\HTTP\Request;
*
* # Creating the main request
*
* $request = Request::from($_SERVER);
*
* # Creating a request from scratch, with the current environment.
*
* $request = Request::from([
*
* Request::OPTION_URI => '/path/to/my/page.html?page=2',
* Request::OPTION_USER_AGENT => 'Mozilla'
* Request::OPTION_IS_GET => true,
* Request::OPTION_IS_XHR => true,
* Request::OPTION_IS_LOCAL => true
*
* ], $_SERVER);
* </pre>
*
* @method Response connect() connect(array $params=null)
* @method Response delete() delete(array $params=null)
* @method Response get() get(array $params=null)
* @method Response head() head(array $params=null)
* @method Response options() options(array $params=null)
* @method Response post() post(array $params=null)
* @method Response put() put(array $params=null)
* @method Response patch() patch(array $params=null)
* @method Response trace() trace(array $params=null)
*
* @property-read Request\Context $context the request's context.
* @property-read Request $parent Parent request.
* @property-read FileList $files The files associated with the request.
*
* @property-read boolean $authorization Authorization of the request.
* @property-read int $content_length Length of the request content.
* @property-read Headers\CacheControl $cache_control
* @property-read string $ip Remote IP of the request.
* @property-read boolean $is_delete Is this a `DELETE` request?
* @property-read boolean $is_get Is this a `GET` request?
* @property-read boolean $is_head Is this a `HEAD` request?
* @property-read boolean $is_options Is this a `OPTIONS` request?
* @property-read boolean $is_patch Is this a `PATCH` request?
* @property-read boolean $is_post Is this a `POST` request?
* @property-read boolean $is_put Is this a `PUT` request?
* @property-read boolean $is_trace Is this a `TRACE` request?
* @property-read boolean $is_local Is this a local request?
* @property-read boolean $is_xhr Is this an Ajax request?
* @property-read string $method Method of the request.
* @property-read string $normalized_path Path of the request normalized using the {@link \ICanBoogie\normalize_url_path()} function.
* @property-read string $path Path info of the request.
* @property-read string $extension The extension of the path.
* @property-read int $port Port of the request.
* @property-read string $query_string Query string of the request.
* @property-read string $script_name Name of the entered script.
* @property-read string $referer Referer of the request.
* @property-read string $user_agent User agent of the request.
* @property-read string $uri URI of the request. The `QUERY_STRING` value of the environment
* is overwritten when the instance is created with the {@link $uri} property.
*
* @see http://en.wikipedia.org/wiki/Uniform_resource_locator
*/
class Request implements \ArrayAccess, \IteratorAggregate, RequestMethods, RequestOptions
{
use AccessorTrait;
static public $methods = [
self::METHOD_CONNECT,
self::METHOD_DELETE,
self::METHOD_GET,
self::METHOD_HEAD,
self::METHOD_OPTIONS,
self::METHOD_POST,
self::METHOD_PUT,
self::METHOD_PATCH,
self::METHOD_TRACE
];
/**
* Current request.
*
* @var Request
*/
static protected $current_request;
/**
* Returns the current request.
*
* @return Request
*/
static public function get_current_request()
{
return self::$current_request;
}
/**
* Parameters extracted from the request path.
*
* @var array
*/
public $path_params = [];
/**
* Parameters defined by the query string.
*
* @var array
*/
public $query_params = [];
/**
* Parameters defined by the request body.
*
* @var array
*/
public $request_params = [];
/**
* Union of {@link $path_params}, {@link $request_params} and {@link $query_params}.
*
* @var array
*/
public $params;
/**
* General purpose container.
*
* @var Request\Context
*/
protected $context;
/**
* The headers of the request.
*
* @var Headers
*/
public $headers;
/**
* Request environment.
*
* @var array
*/
protected $env;
/**
* Files associated with the request.
*
* @var FileList
*/
protected $files;
protected function get_files()
{
if ($this->files instanceof FileList)
{
return $this->files;
}
return $this->files = FileList::from($this->files);
}
public $cookie;
/**
* Parent request.
*
* @var Request
*/
protected $parent;
/**
* A request may be created from the `$_SERVER` super global array. In that case `$_SERVER` is
* used as environment the request is created with the following properties:
*
* - {@link $cookie}: a reference to the `$_COOKIE` super global array.
* - {@link $path_params}: initialized to an empty array.
* - {@link $query_params}: a reference to the `$_GET` super global array.
* - {@link $request_params}: a reference to the `$_POST` super global array.
* - {@link $files}: a reference to the `$_FILES` super global array.
*
* A request may also be created from an array of properties, in which case most of them are
* mapped to the `$env` constructor param. For instance, `is_xhr` set the
* `HTTP_X_REQUESTED_WITH` environment property to 'XMLHttpRequest'. In fact, only the
* following options are preserved:
*
* - Request::OPTION_PATH_PARAMS
* - Request::OPTION_QUERY_PARAMS
* - Request::OPTION_REQUEST_PARAMS
* - Request::OPTION_FILES: The files associated with the request.
* - Request::OPTION_HEADERS: The header fields of the request. If specified, the headers
* available in the environment are ignored.
*
* @param array $properties Properties of the request.
* @param array $env Environment, usually the `$_SERVER` array.
*
* @throws \InvalidArgumentException in attempt to use an unsupported option.
*
* @return Request
*/
static public function from($properties = null, array $env = [])
{
if (!$properties)
{
return new static([], $env);
}
if ($properties === $_SERVER)
{
return static::from_server();
}
if (is_string($properties) || (is_object($properties) && method_exists($properties, '__toString')))
{
return static::from_uri((string) $properties, $env);
}
return static::from_options($properties, $env);
}
/**
* Creates an instance from the `$_SERVER` array.
*
* @return Request
*/
static protected function from_server()
{
return static::from([
self::OPTION_COOKIE => &$_COOKIE,
self::OPTION_PATH_PARAMS => [],
self::OPTION_QUERY_PARAMS => &$_GET,
self::OPTION_REQUEST_PARAMS => &$_POST,
self::OPTION_FILES => &$_FILES // @codeCoverageIgnore
], $_SERVER);
}
/**
* Creates an instance from an URI.
*
* @param string $uri
* @param array $env
*
* @return Request
*/
static protected function from_uri($uri, array $env)
{
return static::from([ self::OPTION_URI => $uri ], $env);
}
/**
* Creates an instance from an array of properties.
*
* @param array $options
* @param array $env
*
* @return Request
*/
static protected function from_options(array $options, array $env)
{
if ($options)
{
static::get_options_mapper()->map($options, $env);
}
if (!empty($env['QUERY_STRING']))
{
parse_str($env['QUERY_STRING'], $options[self::OPTION_QUERY_PARAMS]);
}
return new static($options, $env);
}
/**
* @var RequestOptionsMapper
*/
static private $options_mapper;
/**
* @return RequestOptionsMapper
*/
static protected function get_options_mapper()
{
return self::$options_mapper ?: self::$options_mapper = new RequestOptionsMapper;
}
/**
* Initialize the properties {@link $env}, {@link $headers} and {@link $context}.
*
* If the {@link $params} property is `null` it is set with an union of {@link $path_params},
* {@link $request_params} and {@link $query_params}.
*
* @param array $properties Initial properties.
* @param array $env Environment of the request, usually the `$_SERVER` super global.
*
* @throws MethodNotSupported when the request method is not supported.
*/
protected function __construct(array $properties, array $env = [])
{
$this->context = new Request\Context($this);
$this->env = $env;
foreach ($properties as $property => $value)
{
$this->$property = $value;
}
$this->assert_method($this->method);
if (!$this->headers)
{
$this->headers = new Headers($env);
}
if ($this->params === null)
{
$this->params = $this->path_params + $this->request_params + $this->query_params;
}
}
/**
* Clone {@link $headers} and {@link $context}, and unset {@link $params}.
*/
public function __clone()
{
$this->headers = clone $this->headers;
$this->context = clone $this->context;
unset($this->params);
}
/**
* Alias for {@link send()}.
*
* @return Response The response to the request.
*/
public function __invoke()
{
return $this->send();
}
/**
* Dispatch the request.
*
* The {@link parent} property is used for request chaining.
*
* Note: If an exception is thrown during dispatch {@link $current_request} is not updated!
*
* Note: If the request is changed because of the `$method` or `$params` parameters, it
* is the _changed_ instance that is dispatched, not the actual instance.
*
* @param string|null $method Use this parameter to change the request method.
* @param array|null $params Use this parameter to change the {@link $request_params}
* property of the request.
*
* @return Response The response to the request.
*
* @throws \Exception re-throws exception raised during dispatch.
*/
public function send($method = null, array $params = null)
{
$request = $this->adapt($method, $params);
$this->parent = self::$current_request;
self::$current_request = $request;
try
{
$response = $request->dispatch();
self::$current_request = $request->parent;
return $response;
}
catch (\Exception $e)
{
self::$current_request = $request->parent;
throw $e;
}
}
/**
* Dispatches the request using the {@link dispatch()} helper.
*
* @return Response
*/
protected function dispatch()
{
return dispatch($this); // @codeCoverageIgnore
}
/**
* Asserts that a method is supported.
*
* @param string $method
*
* @throws MethodNotSupported
*/
private function assert_method($method)
{
if (!in_array($method, self::$methods))
{
throw new MethodNotSupported($method);
}
}
/**
* Returns a new instance with the specified changed properties.
*
* @param array $options
*
* @throws \InvalidArgumentException
*
* @return Request
*/
public function with(array $options)
{
$changed = clone $this;
if ($options)
{
static::get_options_mapper()->map($options, $changed->env);
foreach ($options as $option => &$value)
{
$changed->$option = $value;
}
}
return $changed;
}
/**
* Adapts the request to the specified method and params.
*
* @param string $method The method.
* @param array $params The params.
*
* @return Request The same instance is returned if the method is the same and the params
* are `null`. Otherwise a _changed_ request is returned.
*/
protected function adapt($method, array $params = null)
{
if ((!$method || $method == $this->method) && !$params)
{
return $this;
}
$properties = [];
if ($method)
{
$properties = [ self::OPTION_METHOD => $method ];
}
if ($params !== null)
{
$properties[self::OPTION_REQUEST_PARAMS] = $params;
$properties[self::OPTION_PATH_PARAMS] = [];
$properties[self::OPTION_QUERY_PARAMS] = [];
}
return $this->with($properties);
}
/**
* Overrides the method to provide a virtual method for each request method.
*
* Example:
*
* <pre>
* <?php
*
* Request::from('/api/core/aloha')->get();
* </pre>
*
* @param $method
* @param $arguments
*
* @return mixed
*/
public function __call($method, $arguments)
{
$http_method = strtoupper($method);
if (in_array($http_method, self::$methods))
{
array_unshift($arguments, $http_method);
return call_user_func_array([ $this, 'send' ], $arguments);
}
throw new MethodNotDefined($method, $this);
}
/**
* Checks if the specified param exists in the request's params.
*
* @param string $param The name of the parameter.
*
* @return bool
*/
public function offsetExists($param)
{
return isset($this->params[$param]);
}
/**
* Get the specified param from the request's params.
*
* @param string $param The name of the parameter.
*
* @return mixed|null The value of the parameter, or `null` if the parameter does not exists.
*/
public function offsetGet($param)
{
return isset($this->params[$param]) ? $this->params[$param] : null;
}
/**
* Set the specified param to the specified value.
*
* @param string $param The name of the parameter.
* @param mixed $value The value of the parameter.
*/
public function offsetSet($param, $value)
{
$this->params;
$this->params[$param] = $value;
$this->request_params[$param] = $value;
}
/**
* Remove the specified param from the request's parameters.
*
* @param mixed $param
*/
public function offsetUnset($param)
{
unset($this->params[$param]);
}
/**
* Returns an array iterator for the params.
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->params);
}
/**
* Returns the parent request.
*
* @return Request
*/
protected function get_parent()
{
return $this->parent;
}
/**
* Returns the request's context.
*
* @return Request\Context
*/
protected function get_context()
{
return $this->context;
}
/**
* Returns the `Cache-Control` header.
*
* @return Headers\CacheControl
*/
protected function get_cache_control()
{
return $this->headers['Cache-Control'];
}
/**
* Returns the script name.
*
* The setter is volatile, the value is returned from the ENV key `SCRIPT_NAME`.
*
* @return string
*/
protected function get_script_name()
{
return $this->env['SCRIPT_NAME'];
}
/**
* Returns the request method.
*
* This is the getter for the `method` magic property.
*
* The method is retrieved from {@link $env}, if the key `REQUEST_METHOD` is not defined,
* the method defaults to {@link METHOD_GET}.
*
* @return string
*/
protected function get_method()
{
$method = isset($this->env['REQUEST_METHOD']) ? $this->env['REQUEST_METHOD'] : self::METHOD_GET;
if ($method == self::METHOD_POST && !empty($this->request_params['_method']))
{
$method = strtoupper($this->request_params['_method']);
}
return $method;
}
/**
* Returns the query string of the request.
*
* The value is obtained from the `QUERY_STRING` key of the {@link $env} array.
*
* @return string|null
*/
protected function get_query_string()
{
return isset($this->env['QUERY_STRING']) ? $this->env['QUERY_STRING'] : null;
}
/**
* Returns the content length of the request.
*
* The value is obtained from the `CONTENT_LENGTH` key of the {@link $env} array.
*
* @return int|null
*/
protected function get_content_length()
{
return isset($this->env['CONTENT_LENGTH']) ? $this->env['CONTENT_LENGTH'] : null;
}
/**
* Returns the referer of the request.
*
* The value is obtained from the `HTTP_REFERER` key of the {@link $env} array.
*
* @return string|null
*/
protected function get_referer()
{
return isset($this->env['HTTP_REFERER']) ? $this->env['HTTP_REFERER'] : null;
}
/**
* Returns the user agent of the request.
*
* The value is obtained from the `HTTP_USER_AGENT` key of the {@link $env} array.
*
* @return string|null
*/
protected function get_user_agent()
{
return isset($this->env['HTTP_USER_AGENT']) ? $this->env['HTTP_USER_AGENT'] : null;
}
/**
* Checks if the request method is `DELETE`.
*
* @return boolean
*/
protected function get_is_delete()
{
return $this->method == self::METHOD_DELETE;
}
/**
* Checks if the request method is `GET`.
*
* @return boolean
*/
protected function get_is_get()
{
return $this->method == self::METHOD_GET;
}
/**
* Checks if the request method is `HEAD`.
*
* @return boolean
*/
protected function get_is_head()
{
return $this->method == self::METHOD_HEAD;
}
/**
* Checks if the request method is `OPTIONS`.
*
* @return boolean
*/
protected function get_is_options()
{
return $this->method == self::METHOD_OPTIONS;
}
/**
* Checks if the request method is `PATCH`.
*
* @return boolean
*/
protected function get_is_patch()
{
return $this->method == self::METHOD_PATCH;
}
/**
* Checks if the request method is `POST`.
*
* @return boolean
*/
protected function get_is_post()
{
return $this->method == self::METHOD_POST;
}
/**
* Checks if the request method is `PUT`.
*
* @return boolean
*/
protected function get_is_put()
{
return $this->method == self::METHOD_PUT;
}
/**
* Checks if the request method is `TRACE`.
*
* @return boolean
*/
protected function get_is_trace()
{
return $this->method == self::METHOD_TRACE;
}
/**
* Checks if the request is a `XMLHTTPRequest`.
*
* @return boolean
*/
protected function get_is_xhr()
{
return !empty($this->env['HTTP_X_REQUESTED_WITH']) && preg_match('/XMLHttpRequest/', $this->env['HTTP_X_REQUESTED_WITH']);
}
/**
* Checks if the request is local.
*
* @return boolean
*/
protected function get_is_local()
{
$ip = $this->ip;
if ($ip == '::1' || preg_match('/^127\.0\.0\.\d{1,3}$/', $ip))
{
return true;
}
return preg_match('/^0:0:0:0:0:0:0:1(%.*)?$/', $ip);
}
/**
* Returns the remote IP of the request.
*
* If defined, the `HTTP_X_FORWARDED_FOR` header is used to retrieve the original IP.
*
* If the `REMOTE_ADDR` header is empty the request is considered local thus `::1` is returned.
*
* @see http://en.wikipedia.org/wiki/X-Forwarded-For
*
* @return string
*/
protected function get_ip()
{
$forwarded_for = $this->headers['X-Forwarded-For'];
if ($forwarded_for)
{
list($ip) = explode(',', $forwarded_for);
return $ip;
}
return (isset($this->env['REMOTE_ADDR']) ? $this->env['REMOTE_ADDR'] : null) ?: '::1';
}
protected function get_authorization()
{
if (isset($this->env['HTTP_AUTHORIZATION']))
{
return $this->env['HTTP_AUTHORIZATION'];
}
else if (isset($this->env['X-HTTP_AUTHORIZATION']))
{
return $this->env['X-HTTP_AUTHORIZATION'];
}
else if (isset($this->env['X_HTTP_AUTHORIZATION']))
{
return $this->env['X_HTTP_AUTHORIZATION'];
}
else if (isset($this->env['REDIRECT_X_HTTP_AUTHORIZATION']))
{
return $this->env['REDIRECT_X_HTTP_AUTHORIZATION'];
}
return null;
}
/**
* Returns the `REQUEST_URI` environment key.
*
* If the `REQUEST_URI` key is not defined by the environment, the value is fetched from
* the `$_SERVER` array. If the key is not defined in the `$_SERVER` array `null` is returned.
*
* @return string
*/
protected function get_uri()
{
return isset($this->env['REQUEST_URI'])
? $this->env['REQUEST_URI']
: (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null);
}
/**
* Returns the port of the request.
*
* @return int
*/
protected function get_port()
{
return $this->env['REQUEST_PORT'];
}
/**
* Returns the path of the request, that is the `REQUEST_URI` without the query string.
*
* @return string
*/
protected function get_path()
{
$uri = $this->uri;
$qs_pos = strpos($uri, '?');
return ($qs_pos === false) ? $uri : substr($uri, 0, $qs_pos);
}
/**
* Returns the {@link $path} property normalized using the
* {@link \ICanBoogie\normalize_url_path()} function.
*
* @return string
*/
protected function get_normalized_path()
{
return \ICanBoogie\normalize_url_path($this->path);
}
/**
* Returns the extension of the path info.
*
* @return mixed
*/
protected function get_extension()
{
return pathinfo($this->path, PATHINFO_EXTENSION);
}
protected function lazy_set_params($params)
{
return $params;
}
/**
* Returns the union of the {@link path_params}, {@link request_params} and
* {@link query_params} properties.
*
* This method is the getter of the {@link $params} magic property.
*
* @return array
*/
protected function lazy_get_params()
{
return $this->path_params + $this->request_params + $this->query_params;
}
}