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
<?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;
/**
* <Request Trait>
* Provides a set of methods to represent a Psr-7 request stream.
*
* Representation of an outgoing, client-side request.
*
* Per the HTTP specification, this interface includes properties for
* each of the following:
*
* - Protocol version
* - HTTP method
* - URI
* - Headers
* - Message body
*
* During construction, implementations MUST attempt to set the Host header from
* a provided URI if no Host header is provided.
*
* 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.
*
* --------
* Traits provide extended method support to classes without requiring a direct,
* linear chain of inheritance. This allows functions to inherit subsets of
* related methods without declaring a parent class.
*
* In Oroboros core, ALL methods are granted to classes via traits,
* and the classes themselves are just containers that correlate their methods
* to an interface they are expected to honor. This approach maximizes
* interoperability, by entirely removing class inheritance as a requirement
* for extension of any class in this system.
*
* 3rd parties using this package are not expected to follow this approach,
* but ALL of our internal class and logic structure does.
* --------
*
* @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\RequestContract
* @satisfies \Psr\Http\Message\RequestInterface
*/
trait RequestTrait
{
/**
* Provides Psr-7 message wrapper functionality.
*/
use \oroboros\core\traits\libraries\stream\MessageTrait;
/**
* Represents the current request uri.
* @var \Psr\Http\Message\UriInterface
*/
private $_request_uri;
/**
* If no request uri was provided, this value will be false.
* @var bool
*/
private $_request_uri_provided = false;
/**
* Represents the current request method.
* @var \oroboros\core\utilities\http\RequestMethod
*/
private $_request_method;
/**
* Represents whether the request has been correctly initialized.
* @var bool
*/
private $_request_is_initialized = false;
/**
* -------------------------------------------------------------------------
* Contract Methods
*
* These methods satisfy the public api defined in the request contract
*
* @satisfies \oroboros\core\interfaces\contract\libraries\request\RequestContract
*
* -------------------------------------------------------------------------
*/
/**
* <Request Constructor>
* Constructs a new instance of a Psr-7 message wrapper.
* @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.
* @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 )
{
$this->_initializeRequest( $body, $headers, $protocol, $host, $uri,
$method );
}
/**
* Retrieves the message's request target.
*
* Retrieves the message's request-target either as it will appear (for
* clients), as it appeared at request (for servers), or as it was
* specified for the instance (see withRequestTarget()).
*
* In most cases, this will be the origin-form of the composed URI,
* unless a value was provided to the concrete implementation (see
* withRequestTarget() below).
*
* If no URI is available, and no request-target has been specifically
* provided, this method MUST return the string "/".
*
* @return string
*/
public function getRequestTarget()
{
if ( !$this->_request_uri_provided )
{
return '/';
}
return (string) $this->_request_uri;
}
/**
* Return an instance with the specific request-target.
*
* If the request needs a non-origin-form request-target — e.g., for
* specifying an absolute-form, authority-form, or asterisk-form —
* this method may be used to create an instance with the specified
* request-target, verbatim.
*
* 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
* changed request target.
*
* @see http://tools.ietf.org/html/rfc7230#section-5.3 (for the various
* request-target forms allowed in request messages)
* @param mixed $requestTarget
* @return static
*/
public function withRequestTarget( $requestTarget )
{
$values = $this->_getMessageValues();
$values['uri'] = $requestTarget;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieves the HTTP method of the request.
*
* @return string Returns the request method.
*/
public function getMethod()
{
return (string) $this->_request_method;
}
/**
* Return an instance with the provided HTTP method.
*
* While HTTP method names are typically all uppercase characters, HTTP
* method names are case-sensitive and thus implementations SHOULD NOT
* modify the given string.
*
* 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
* changed request method.
*
* @param string $method Case-sensitive method.
* @return static
* @throws \InvalidArgumentException for invalid HTTP methods.
*/
public function withMethod( $method )
{
$this->_validateRequestMethod( $method );
$values = $this->_getMessageValues();
$values['method'] = $method;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieves the URI instance.
*
* This method MUST return a UriInterface instance.
*
* @see http://tools.ietf.org/html/rfc3986#section-4.3
* @return UriInterface Returns a UriInterface instance
* representing the URI of the request.
*/
public function getUri()
{
return $this->_request_uri;
}
/**
* Returns an instance with the provided URI.
*
* This method MUST update the Host header of the returned request by
* default if the URI contains a host component. If the URI does not
* contain a host component, any pre-existing Host header MUST be carried
* over to the returned request.
*
* You can opt-in to preserving the original state of the Host header by
* setting `$preserveHost` to `true`. When `$preserveHost` is set to
* `true`, this method interacts with the Host header in the following ways:
*
* - If the Host header is missing or empty, and the new URI contains
* a host component, this method MUST update the Host header in the returned
* request.
* - If the Host header is missing or empty, and the new URI does not contain a
* host component, this method MUST NOT update the Host header in the returned
* request.
* - If a Host header is present and non-empty, this method MUST NOT update
* the Host header in the returned request.
*
* 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
* new UriInterface instance.
*
* @see http://tools.ietf.org/html/rfc3986#section-4.3
* @param UriInterface $uri New request URI to use.
* @param bool $preserveHost Preserve the original state of the Host header.
* @return static
*/
public function withUri( \Psr\Http\Message\UriInterface $uri,
$preserveHost = false )
{
$values = $this->_getMessageValues();
$host = $host_key = false;
foreach ( $values['headers'] as
$key =>
$value )
{
if ( strtolower( $key ) === 'host' )
{
$host = $value;
$host_key = $key;
break;
}
}
if ( (!$preserveHost && $uri->getHost() !== '') //new host due to explicit request
|| ($preserveHost && $uri->getHost() !== '' && !$host_key) //new host due to missing host header
|| ($preserveHost && $uri->getHost() !== '' && $host == '') //new host due to host not set
)
{
$host = $uri->getHost();
$host_key = ($host_key)
? $host_key
: 'Host';
$values['headers'][$host_key] = $host;
}
$values['uri'] = (string) $uri;
$tmp = $values;
foreach ($tmp as $key => $value)
{
if (!in_array($key, array('body', 'protocol', 'headers', 'host', 'uri', 'method')))
{
unset($tmp[$key]);
}
}
return $this->_instantiateMessageNewInstance( $values );
}
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
* <Request Initialization Method>
* Creates a ready instance of a Psr-7 message stream.
* @param mixed $body
* @param resource|string $source
* @param array $headers
* @param string $protocol
* @return void
*/
protected function _initializeRequest( $body, array $headers = null,
$protocol = null, $host = null, $uri = null, $method = null )
{
$this->_initializeMessage( $body, $headers, $protocol, $host );
$this->_setRequestHostHeader( $host, $headers );
if ( is_null( $uri ) )
{
$uri = $this->_getRequestDefaultUri();
} else
{
$this->_request_uri_provided = true;
}
$this->_setRequestUri( $uri );
if ( is_null( $method ) )
{
$method = $this->_getRequestDefaultRequestMethod();
}
$this->_setRequestMethod( $method );
$this->_request_is_initialized = true;
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* Validates the host. Host must be a valid url, localhost, IPv4 or IPv6
* @param string $host
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateRequestHost( $host )
{
if ( !is_string( $host ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string', gettype( $host ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the uri. Uri must be a valid url, localhost, IPv4 or IPv6
* @param string $uri
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateRequestUri( $uri )
{
if ( !is_string( $uri ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string', gettype( $uri ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Validates the request method. Request method must be a valid HTTP request method (GET, POST, PUT, DELETE, etc)
* @param string $method
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateRequestMethod( $method )
{
if ( !is_string( $method ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string', gettype( $method ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Creates an object that represents the request uri, and stores it internally.
* @param string $uri
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid uri is provided
*/
private function _setRequestUri( $uri )
{
$this->_validateRequestUri( $uri );
$this->_request_uri = new \oroboros\core\libraries\uri\Uri( $uri );
}
/**
* Creates an object that represents the request method, and stores it internally.
* @param string $method
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid request method is provided
*/
private function _setRequestMethod( $method )
{
$this->_validateRequestMethod( $method );
$this->_request_method = new \oroboros\core\utilities\http\RequestMethod( $method );
}
/**
* Sets the host header, if it is not provided.
* @param string $host
* @param array $headers
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid hostname is provided
*/
private function _setRequestHostHeader( $host = null, $headers = null )
{
$hostname = $this->_getRequestDefaultHostname();
$host_header_name = 'Host';
if ( !is_null( $host ) )
{
$hostname = $host;
} elseif ( is_array( $headers ) )
{
foreach ( $headers as
$key =>
$header )
{
if ( strtolower( $key ) === 'host' )
{
$hostname = is_array( $header )
? array_pop( $header )
: $header;
$host_header_name = $key;
}
}
}
$this->_validateRequestHost( $hostname );
$this->_message_headers[$host_header_name] = new \oroboros\core\utilities\http\Header( $host_header_name,
$hostname );
}
/**
* Returns a default hostname if none is provided.
* @return string
*/
private function _getRequestDefaultHostname()
{
if ( !\oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
//This request came from the command line. We can explicitly pass the local IP address.
//In most cases, this value will be entirely ignored for CLI messages.
//In the event that a message is outbound or used in a cURL wrapper or similar
//a host should be provided on instantiation of this object.
return '127.0.0.1';
}
//This request came from HTTP, so we will use
//the default host name established by PHP as the default.
return $_SERVER['HTTP_HOST'];
}
/**
* Returns the default local page uri if none is provided,
* or the localized IP address if current execution came from CLI.
* @return string
*/
private function _getRequestDefaultUri()
{
if ( !\oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
//This request came from the command line. We can explicitly pass the local IP address.
//In most cases, this value will be entirely ignored for CLI messages.
//In the event that a message is outbound or used in a cURL wrapper or similar
//a host should be provided on instantiation of this object.
return '127.0.0.1';
}
//This request came from HTTP, so we will use
//the default host name established by PHP as the default.
$uri = \oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_SSL
? 'https'
: 'http' . '://' . $_SERVER['HTTP_HOST'] . ':80' . $_SERVER['REQUEST_URI'];
return $uri;
}
/**
* Returns the default local uri request method if none is provided,
* or the GET if it could not be determined (or if the request came from CLI).
* @return string
*/
private function _getRequestDefaultRequestMethod()
{
if ( !\oroboros\core\interfaces\enumerated\environment\HttpEnvironmentApi::IS_HTTP )
{
//This request came from the command line. We can explicitly pass the local IP address.
//In most cases, this value will be entirely ignored for CLI messages.
//In the event that a message is outbound or used in a cURL wrapper or similar
//a host should be provided on instantiation of this object.
return '127.0.0.1';
}
return ( isset( $_SERVER['REQUEST_METHOD'] )
? $_SERVER['REQUEST_METHOD']
: 'GET');
}
/**
* 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
);
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\RequestTrait
*/
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'] );
return $instance;
}
}