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 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 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
<?php
/*
* The MIT License
*
* @author Brian Dayhoff <mopsyd@me.com>
* @copyright (c) 2017, Brian Dayhoff <mopsyd@me.com> all rights reserved.
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace oroboros\core\traits\libraries\request;
/**
* <Server Request Trait>
* Provides a set of methods to represent a Psr-7 server request stream.
*
* Representation of an incoming, server-side HTTP request.
*
* Per the HTTP specification, this interface includes properties for
* each of the following:
*
* - Protocol version
* - HTTP method
* - URI
* - Headers
* - Message body
*
* Additionally, it encapsulates all data as it has arrived at the
* application from the CGI and/or PHP environment, including:
*
* - The values represented in $_SERVER.
* - Any cookies provided (generally via $_COOKIE)
* - Query string arguments (generally via $_GET, or as parsed via parse_str())
* - Upload files, if any (as represented by $_FILES)
* - Deserialized body parameters (generally from $_POST)
*
* $_SERVER values MUST be treated as immutable, as they represent application
* state at the time of request; as such, no methods are provided to allow
* modification of those values. The other values provide such methods, as they
* can be restored from $_SERVER or the request body, and may need treatment
* during the application (e.g., body parameters may be deserialized based on
* content type).
*
* Additionally, this interface recognizes the utility of introspecting a
* request to derive and match additional parameters (e.g., via URI path
* matching, decrypting cookie values, deserializing non-form-encoded body
* content, matching authorization headers to users, etc). These parameters
* are stored in an "attributes" property.
*
* Requests are considered immutable; all methods that might change state MUST
* be implemented such that they retain the internal state of the current
* message and return an instance that contains the changed state.
*
* --------
*
* @author Brian Dayhoff <mopsyd@me.com>
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
* @link bitbucket.org/oroborosframework/oroboros-core/wiki/development/api/traits.md
* @category traits
* @package oroboros/core
* @subpackage psr7
* @version 0.2.4
* @since 0.2.4-alpha
* @satisfies \oroboros\core\interfaces\contract\libraries\request\ServerRequestContract
* @satisfies \Psr\Http\Message\ServerRequestInterface
*/
trait ServerRequestTrait
{
/**
* Provides Psr-7 request message wrapper functionality.
*/
use RequestTrait;
/**
* Represents the server request parameters
* @var array
*/
private $_server_request_params = array();
/**
* Represents the server request cookies.
* @var array
*/
private $_server_request_cookies = array();
/**
* Represents the server request query
* @var array
*/
private $_server_request_query = array();
/**
* Represents the server request uploaded files
* @var array
*/
private $_server_request_files = array();
/**
* Represents the server request parsed body (POST) content
* @var array
*/
private $_server_request_parsed = array();
/**
* Represents the server request attributes
* @var array
*/
private $_server_request_attributes = array();
/**
* Represents whether the server request has been correctly initialized.
* @var bool
*/
private $_server_request_is_initialized = false;
/**
* -------------------------------------------------------------------------
* Contract Methods
*
* These methods satisfy the public api defined in the server request contract
*
* @satisfies \oroboros\core\interfaces\contract\libraries\request\ServerRequestContract
*
* -------------------------------------------------------------------------
*/
/**
* <Server Request Constructor>
* Instantiates an instance of a Psr-7 server request object.
* @param scalar|resource|\Psr\Http\Message\StreamInterface $body This is the only required value for the constructor, and represents a message body as a scalar value, resource pointer, or instance of a stream interface.
* @param type $headers (optional) If provided, represents an array of headers to construct with the message.
* @param type $protocol (optional) If provided, the HTTP request protocol will be set to this value. Default value is "1.1"
* @param string $host (optional) If provided, a host header will be explicitly set to this value. If not supplied, it will return the current host, or 127.0.0.1 if the host could not be determined or the request originated from CLI.
* @param string $uri (optional) If provided, an endpoint uri will be explicitly set to this value. If not supplied, it will return the current host, or 127.0.0.1 if the host could not be determined or the request originated from CLI.
* @param string $method (optional) If provided, a request method will be explicitly set to this value. If not supplied, it will return the same request method of the current page load, or GET if it could not be determined or the request originated from CLI.
* @param array $params An array of parameters, following the convention of the $_SERVER superglobal
* @param array $cookies An array of parameters, following the convention of the $_COOKIE superglobal
* @param array $query An array of parameters, following the convention of the $_GET superglobal
* @param array $files An array of parameters, following the convention of the $_FILES superglobal
* @param array $parsed An array of parameters, following the convention of the $_POST superglobal
* @param array $attributes (optional) An array of request-specific parameters
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if any passed parameters do not validate
*/
public function __construct(
$body, array $headers = null, $protocol = null, $host = null, $uri = null,
$method = null, array $params = array(), array $cookies = array(),
array $query = array(), array $files = array(), array $parsed = array(),
array $attributes = array()
)
{
$this->_initializeServerRequest( $body, $headers, $protocol, $host,
$uri, $method, $params, $cookies, $query, $files, $parsed,
$attributes );
}
/**
* <Server Request Creation Method>
* Provides a simpler way of instantiating a new object based
* on only the superglobal state or equivalent, so that the
* provided constructor does not interfere with the
* Liskov Substitution Principle, but in general use,
* the object is not cumbersome to generate either.
*
* This is the suggested means of creating an instance
* with your own parameters.
*
* If you would like to automatically create an instance from existing superglobals,
* it is suggested to instead use the fromGlobals method.
*
* @see \oroboros\core\traits\libraries\request\ServerRequestTrait::fromGlobals()
*
* @param array $params
* @param array $cookies
* @param array $query
* @param array $files
* @param array $parsed
* @param array $attributes
* @return \oroboros\core\traits\libraries\request\ServerRequestTrait
* @throws \oroboros\core\utilities\exception\InvalidArgumentException If instantiation cannot occur due to bad parameters
*/
public static function create(
array $params = array(), array $cookies = array(), array $query = array(),
array $files = array(), array $parsed = array(),
array $attributes = array()
)
{
$class = get_called_class();
return new $class( null, null, null, null, null, null, $params,
$cookies, $query, $files, $parsed, $attributes );
}
/**
* <Server Request Automatic Generation Method>
* This is the suggested means of creating an instance of an object
* using this trait automatically from existing globals.
*
* In the event that you have to pass your own parameters,
* it is suggested to use the create method instead.
*
* @see \oroboros\core\traits\libraries\request\ServerRequestTrait::create()
*
* Constructs an instance of the current class using the current superglobals.
* As a safety measure, superglobals will be spoofed as empty arrays if they
* are not available (ie: if you have not called session_start, or the
* request if from CLI and therefore does not have $_GET or $_POST).
*
* This method will use $_SESSION for the $attributes
* parameter of the constructor.
*
* If the request originated from CLI, $argv will be used in place of $_GET
* if it is available. The first parameter if $argv is to be omitted, as it
* only designates the php script name of the original request, and is
* also available in $_SERVER.
*
* The $_REQUEST superglobal is to be ignored,
* as all of it's values are provided in $_GET and $_POST.
*
* @return \oroboros\core\traits\libraries\request\ServerRequestTrait
*/
public static function fromGlobals()
{
if ( !isset( $_SERVER ) )
{
$_SERVER = array();
}
if ( !isset( $_COOKIE ) )
{
$_COOKIE = array();
}
if ( !isset( $_GET ) )
{
$_GET = array();
if ( \oroboros\core\interfaces\enumerated\environment\CgiEnvironmentApi::IS_CLI )
{
//use $argv in place of $_GET, if $argv is available.
//omit the first parameter of $argv
global $argv;
if ( is_array( $argv ) )
{
$get = $argv;
array_shift( $get );
$_GET = $get;
}
}
}
if ( !isset( $_FILES ) )
{
$_FILES = array();
}
if ( !isset( $_POST ) )
{
$_POST = array();
}
if ( !isset( $_SESSION ) )
{
$_SESSION = array();
}
$class = get_called_class();
return new $class( null, null, null, null, null, null, $_SERVER,
$_COOKIE, $_GET, $_FILES, $_POST, $_SESSION );
}
/**
* Retrieve server parameters.
*
* Retrieves data related to the incoming request environment,
* typically derived from PHP's $_SERVER superglobal. The data IS NOT
* REQUIRED to originate from $_SERVER.
*
* @return array
*/
public function getServerParams()
{
return $this->_server_request_params->toArray();
}
/**
* Retrieve cookies.
*
* Retrieves cookies sent by the client to the server.
*
* The data MUST be compatible with the structure of the $_COOKIE
* superglobal.
*
* @return array
*/
public function getCookieParams()
{
return $this->_server_request_cookies->toArray();
}
/**
* Return an instance with the specified cookies.
*
* The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
* be compatible with the structure of $_COOKIE. Typically, this data will
* be injected at instantiation.
*
* This method MUST NOT update the related Cookie header of the request
* instance, nor related values in the server params.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* updated cookie values.
*
* @param array $cookies Array of key/value pairs representing cookies.
* @return static
*/
public function withCookieParams( array $cookies )
{
$this->_validateServerRequestCookies( $cookies );
$values = $this->_getMessageValues();
$values['cookies'] = $cookies;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieve query string arguments.
*
* Retrieves the deserialized query string arguments, if any.
*
* Note: the query params might not be in sync with the URI or server
* params. If you need to ensure you are only getting the original
* values, you may need to parse the query string from `getUri()->getQuery()`
* or from the `QUERY_STRING` server param.
*
* @return array
*/
public function getQueryParams()
{
return $this->_server_request_query->toArray();
}
/**
* Return an instance with the specified query string arguments.
*
* These values SHOULD remain immutable over the course of the incoming
* request. They MAY be injected during instantiation, such as from PHP's
* $_GET superglobal, or MAY be derived from some other value such as the
* URI. In cases where the arguments are parsed from the URI, the data
* MUST be compatible with what PHP's parse_str() would return for
* purposes of how duplicate query parameters are handled, and how nested
* sets are handled.
*
* Setting query string arguments MUST NOT change the URI stored by the
* request, nor the values in the server params.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* updated query string arguments.
*
* @param array $query Array of query string arguments, typically from
* $_GET.
* @return static
*/
public function withQueryParams( array $query )
{
$this->_validateServerRequestQuery( $query );
$values = $this->_getMessageValues();
$values['query'] = $query;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieve normalized file upload data.
*
* This method returns upload metadata in a normalized tree, with each leaf
* an instance of Psr\Http\Message\UploadedFileInterface.
*
* These values MAY be prepared from $_FILES or the message body during
* instantiation, or MAY be injected via withUploadedFiles().
*
* @return array An array tree of UploadedFileInterface instances; an empty
* array MUST be returned if no data is present.
*/
public function getUploadedFiles()
{
return $this->_server_request_files->toArray();
}
/**
* Create a new instance with the specified uploaded files.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* updated body parameters.
*
* @param array $uploadedFiles An array tree of UploadedFileInterface instances.
* @return static
* @throws \InvalidArgumentException if an invalid structure is provided.
*/
public function withUploadedFiles( array $uploadedFiles )
{
$this->_validateServerRequestFiles( $uploadedFiles );
$values = $this->_getMessageValues();
$values['files'] = $uploadedFiles;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieve any parameters provided in the request body.
*
* If the request Content-Type is either application/x-www-form-urlencoded
* or multipart/form-data, and the request method is POST, this method MUST
* return the contents of $_POST.
*
* Otherwise, this method may return any results of deserializing
* the request body content; as parsing returns structured content, the
* potential types MUST be arrays or objects only. A null value indicates
* the absence of body content.
*
* @return null|array|object The deserialized body parameters, if any.
* These will typically be an array or object.
*/
public function getParsedBody()
{
return $this->_server_request_parsed->toArray();
}
/**
* Return an instance with the specified body parameters.
*
* These MAY be injected during instantiation.
*
* If the request Content-Type is either application/x-www-form-urlencoded
* or multipart/form-data, and the request method is POST, use this method
* ONLY to inject the contents of $_POST.
*
* The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
* deserializing the request body content. Deserialization/parsing returns
* structured data, and, as such, this method ONLY accepts arrays or objects,
* or a null value if nothing was available to parse.
*
* As an example, if content negotiation determines that the request data
* is a JSON payload, this method could be used to create a request
* instance with the deserialized parameters.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* updated body parameters.
*
* @param null|array|object $data The deserialized body data. This will
* typically be in an array or object.
* @return static
* @throws \InvalidArgumentException if an unsupported argument type is
* provided.
*/
public function withParsedBody( $data )
{
$this->_validateServerRequestParsed( $data );
$values = $this->_getMessageValues();
$values['parsed'] = $data;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieve attributes derived from the request.
*
* The request "attributes" may be used to allow injection of any
* parameters derived from the request: e.g., the results of path
* match operations; the results of decrypting cookies; the results of
* deserializing non-form-encoded message bodies; etc. Attributes
* will be application and request specific, and CAN be mutable.
*
* @return mixed[] Attributes derived from the request.
*/
public function getAttributes()
{
return $this->_server_request_attributes->toArray();
}
/**
* Retrieve a single derived request attribute.
*
* Retrieves a single derived request attribute as described in
* getAttributes(). If the attribute has not been previously set, returns
* the default value as provided.
*
* This method obviates the need for a hasAttribute() method, as it allows
* specifying a default value to return if the attribute is not found.
*
* @see getAttributes()
* @param string $name The attribute name.
* @param mixed $default Default value to return if the attribute does not exist.
* @return mixed
*/
public function getAttribute( $name, $default = null )
{
if ( $this->_server_request_attributes->has( $name ) )
{
return $this->_server_request_attributes->get( $name );
}
return $default;
}
/**
* Return an instance with the specified derived request attribute.
*
* This method allows setting a single derived request attribute as
* described in getAttributes().
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that has the
* updated attribute.
*
* @see getAttributes()
* @param string $name The attribute name.
* @param mixed $value The value of the attribute.
* @return static
*/
public function withAttribute( $name, $value )
{
$values = $this->_getMessageValues();
$values['attributes'][$name] = $value;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Return an instance that removes the specified derived request attribute.
*
* This method allows removing a single derived request attribute as
* described in getAttributes().
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return an instance that removes
* the attribute.
*
* @see getAttributes()
* @param string $name The attribute name.
* @return static
*/
public function withoutAttribute( $name )
{
$values = $this->_getMessageValues();
if ( array_key_exists( $name, $values['attributes'] ) )
{
unset( $values['attributes'][$name] );
}
return $this->_instantiateMessageNewInstance( $values );
}
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
* <Server Request Initialization Method>
* Creates a ready instance of a Psr-7 server request message stream.
* @param array $params An array of parameters, following the convention of the $_SERVER superglobal
* @param array $cookies An array of parameters, following the convention of the $_COOKIES superglobal
* @param array $query An array of parameters, following the convention of the $_GET superglobal
* @param array $files An array of parameters, following the convention of the $_FILES superglobal
* @param array $parsed An array of parameters, following the convention of the $_POST superglobal
* @param array $attributes (optional) An array of request-specific parameters
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if any passed parameters do not validate
*/
protected function _initializeServerRequest( $body, array $headers = null,
$protocol = null, $host = null, $uri = null, $method = null,
array $params = array(), array $cookies = array(),
array $query = array(), array $files = array(), array $parsed = array(),
array $attributes = array() )
{
$this->_setServerRequestParams( $params );
$this->_setServerRequestCookies( $cookies );
$this->_setServerRequestQuery( $query );
$this->_setServerRequestFiles( $files );
$this->_setServerRequestParsed( $parsed );
$this->_setServerRequestAttributes( $attributes );
//Initialize the request,
//using values derived from the
//server request if not explicitly passed
$this->_initializeRequest(
is_null( $body )
? $this->_getServerRequestBodyValue()
: $body,
is_null( $headers )
? $this->_getServerRequestHeadersValue()
: $headers,
is_null( $protocol )
? $this->_getServerRequestProtocolValue()
: $protocol,
is_null( $host )
? $this->_getServerRequestHostValue()
: $host,
is_null( $uri )
? $this->_getServerRequestUriValue()
: $uri,
is_null( $method )
? $this->_getServerRequestMethodValue()
: $method
);
$this->_server_request_is_initialized = true;
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* Validates the params. Params must be an array compatible with the
* structure of the $_SERVER superglobal.
* @param string $params
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestParams( $params )
{
if ( !is_array( $params ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $params ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the cookies. Cookies must be an array compatible with the
* structure of the $_COOKIES superglobal.
* @param string $cookies
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestCookies( $cookies )
{
if ( !is_array( $cookies ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $cookies ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the cookies. Cookies must be an array compatible with the
* structure of the $_GET superglobal.
* @param string $query
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestQuery( $query )
{
if ( !is_array( $query ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $query ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the files. Files must be an array compatible with the
* structure of the $_FILES superglobal.
* @param string $files
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestFiles( $files )
{
if ( !is_array( $files ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $files ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the parsed values. Parsed values must be an array compatible with the
* structure of the $_POST superglobal.
* @param string $parsed
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestParsed( $parsed )
{
if ( !is_array( $parsed ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $parsed ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the attributes. Attributes must be an array compatible with the
* structure of the $_POST superglobal.
* @param string $attributes
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateServerRequestAttributes( $attributes )
{
if ( !is_array( $attributes ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'array', gettype( $attributes ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Creates an object that represents the provided params, and stores it internally.
* @param string $params
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid params array is provided
*/
private function _setServerRequestParams( $params )
{
$this->_validateServerRequestParams( $params );
$this->_server_request_params = new \oroboros\core\libraries\container\Collection( $params );
}
/**
* Creates an object that represents the cookies, and stores it internally.
* @param string $cookies
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid cookies array is provided
*/
private function _setServerRequestCookies( $cookies )
{
$this->_validateServerRequestCookies( $cookies );
$this->_server_request_cookies = new \oroboros\core\libraries\container\Collection( $cookies );
}
/**
* Creates an object that represents the query, and stores it internally.
* @param string $query
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid query array is provided
*/
private function _setServerRequestQuery( $query )
{
$this->_validateServerRequestQuery( $query );
$this->_server_request_query = new \oroboros\core\libraries\container\Collection( $query );
}
/**
* Creates an object that represents the uploaded files, and stores it internally.
* @param string $files
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid files array is provided
*/
private function _setServerRequestFiles( $files )
{
$this->_validateServerRequestFiles( $files );
$this->_server_request_files = \oroboros\core\libraries\file\FileUpload::getUploadedFileCollection( $files );
}
/**
* Creates an object that represents the parsed values, and stores it internally.
* @param string $parsed
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid parsed array is provided
*/
private function _setServerRequestParsed( $parsed )
{
$this->_validateServerRequestParsed( $parsed );
$this->_server_request_parsed = new \oroboros\core\libraries\container\Collection( $parsed );
}
/**
* Creates an object that represents the attributes, and stores it internally.
* @param string $attributes
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid attribute array is provided
*/
private function _setServerRequestAttributes( $attributes )
{
$this->_validateServerRequestAttributes( $attributes );
$this->_server_request_attributes = new \oroboros\core\libraries\container\Collection( $attributes );
}
/**
* Provides a value to satisfy the underlying stream body value,
* based on the server request values.
* @return resource
*/
private function _getServerRequestBodyValue()
{
//If this is a CLI request, we will use STDIN.
//If it is an http request, we will use php://input
//If php://input is not available (PHP version < 5.6 and already read),
//we will use a memory resource.
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
try
{
$res = fopen( 'php://input', 'rb' );
} catch ( \Exception $e )
{
//If this failed, use a memory stream.
//The server request has little need for the resource anyhow.
$res = fopen( 'php://memory', 'r+b' );
}
return $res;
}
//use STDIN for CLI requests
return STDIN;
}
/**
* Provides a value to satisfy the underlying message headers value,
* based on the server request values.
* @return array
*/
private function _getServerRequestHeadersValue()
{
$headers = array();
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
$headers = getallheaders();
}
return $headers;
}
/**
* Provides a value to satisfy the underlying message protocol value,
* based on the server request values.
* @return string
*/
private function _getServerRequestProtocolValue()
{
$protocol = $this->_message_protocol_default;
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
if ( $this->_server_request_params->has( 'SERVER_PROTOCOL' ) )
{
$protocol = str_replace( 'HTTP/', null,
$this->_server_request_params->get( 'SERVER_PROTOCOL' ) );
}
}
return $protocol;
}
/**
* Provides a value to satisfy the underlying request host value,
* based on the server request values.
* @return string
*/
private function _getServerRequestHostValue()
{
$host = '127.0.0.1';
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
$host = 'localhost';
if ( $this->_server_request_params->has( 'HTTP_HOST' ) )
{
$host = $this->_server_request_params->get( 'HTTP_HOST' );
}
}
return $host;
}
/**
* Provides a value to satisfy the underlying request uri value,
* based on the server request values.
* @return string
*/
private function _getServerRequestUriValue()
{
$uri = '127.0.0.1';
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
$uri = '';
if ( $this->_server_request_params->has( 'HTTP_HOST' ) )
{
$uri = 'http'
. ( ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_SSL )
? 's'
: null )
. '://' . $this->_server_request_params->get( 'HTTP_HOST' );
}
if ( $this->_server_request_params->has( 'REQUEST_URI' ) )
{
$uri .= $this->_server_request_params->get( 'REQUEST_URI' );
}
}
return $uri;
}
/**
* Provides a value to satisfy the underlying request method value,
* based on the server request values.
* @return string
*/
private function _getServerRequestMethodValue()
{
$method = 'GET';
if ( \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
if ( $this->_server_request_params->has( 'REQUEST_METHOD' ) )
{
$method = $this->_server_request_params->get( 'REQUEST_METHOD' );
}
}
return $method;
}
/**
* Returns the current internal values,
* for instantiation of new object instances while
* rendering the current object immutable.
* @return array
*/
private function _getMessageValues()
{
$values = array(
'body' => $this->_stream,
'protocol' => (string) $this->_message_protocol,
'headers' => $this->getHeaders(),
'host' => null,
'uri' => ($this->_request_uri_provided)
? (string) $this->_request_uri
: null,
'method' => (string) $this->_request_method,
'params' => $this->_server_request_params->toArray(),
'cookies' => $this->_server_request_cookies->toArray(),
'query' => $this->_server_request_query->toArray(),
'files' => $this->_server_request_files->toArray(),
'parsed' => $this->_server_request_parsed->toArray(),
'attributes' => $this->_server_request_attributes->toArray()
);
foreach ( $this->_message_headers as
$key =>
$header )
{
if ( strtolower( $key ) === 'host' )
{
$values['host'] = $header->getValueString();
break;
}
}
return $values;
}
/**
* Creates a new instance based off of the default parameters,
* substituting any values passed in.
* @param array $params
* @return \oroboros\core\traits\libraries\request\ServerRequestTrait
*/
private function _instantiateMessageNewInstance( array $params = null )
{
$values = $this->_getMessageValues();
if ( !is_null( $params ) )
{
foreach ( $params as
$key =>
$value )
{
$values[$key] = $value;
}
}
$class = get_class( $this );
$instance = new $class( $values['body'], $values['headers'],
$values['protocol'], $values['host'], $values['uri'],
$values['method'], $params['params'], $params['cookies'],
$params['query'], $params['files'], $params['parsed'],
$params['attributes'] );
return $instance;
}
}