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
<?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\stream;
/**
* <Message Trait>
* Provides a set of methods to represent a Psr-7 message stream.
*
* HTTP messages consist of requests from a client to a server and responses
* from a server to a client. This interface defines the methods common to
* each.
*
* Messages 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\message\MessageContract
* @satisfies \Psr\Http\Message\MessageInterface
* @link http://www.ietf.org/rfc/rfc7230.txt
* @link http://www.ietf.org/rfc/rfc7231.txt
*/
trait MessageTrait
{
/**
* Provides Psr-7 stream wrapper functionality.
*/
use StreamTrait;
/**
* Represents the header values of headers passed in for the message.
* @var array
*/
private $_message_headers = array();
/**
* Represents valid HTTP request methods.
* If HTTP/2 becomes prominent and supported at a later date,
* it will be added here also.
* @var array
*/
private $_message_valid_protocols = array(
'1.0',
'1.1',
);
/**
* Represents the default HTTP transfer protocol.
* @var string
*/
private $_message_protocol_default = '1.1';
/**
* The current message protocol.
* @var \oroboros\core\utilities\http\Protocol
*/
private $_message_protocol;
/**
* Represents whether the message is properly initialized.
* @var bool
*/
private $_message_is_initialized = false;
private static $_message_headers_valid = array(
'request' => array(),
'response' => array()
);
/**
* -------------------------------------------------------------------------
* Contract Methods
*
* These methods satisfy the public api defined in the message contract
*
* @satisfies \oroboros\core\interfaces\contract\libraries\stream\MessageContract
*
* -------------------------------------------------------------------------
*/
/**
* <Message 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"
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if any passed parameters do not validate
*/
public function __construct( $body, array $headers = null, $protocol = null )
{
$this->_initializeMessage( $body, $headers, $protocol );
}
/**
* Retrieves the HTTP protocol version as a string.
*
* The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
*
* @return string HTTP protocol version.
*/
public function getProtocolVersion()
{
return (string) $this->_message_protocol;
}
/**
* Return an instance with the specified HTTP protocol version.
*
* The version string MUST contain only the HTTP version number (e.g.,
* "1.1", "1.0").
*
* 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 protocol version.
*
* @param string $version HTTP protocol version
* @return static
*/
public function withProtocolVersion( $version )
{
if ( !is_string( $version ) && !in_array( $version,
$this->_message_valid_protocols ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__,
'string (' . implode( ',', $this->_message_valid_protocols ) . ')',
gettype( $version ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
$values = $this->_getMessageValues();
$values['protocol'] = $version;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Retrieves all message header values.
*
* The keys represent the header name as it will be sent over the wire, and
* each value is an array of strings associated with the header.
*
* // Represent the headers as a string
* foreach ($message->getHeaders() as $name => $values) {
* echo $name . ': ' . implode(', ', $values);
* }
*
* // Emit headers iteratively:
* foreach ($message->getHeaders() as $name => $values) {
* foreach ($values as $value) {
* header(sprintf('%s: %s', $name, $value), false);
* }
* }
*
* While header names are not case-sensitive, getHeaders() will preserve the
* exact case in which headers were originally specified.
*
* @return string[][] Returns an associative array of the message's headers.
* Each key MUST be a header name, and each value MUST be an array of
* strings for that header.
*/
public function getHeaders()
{
return $this->_getMessageHeaders();
}
/**
* Checks if a header exists by the given case-insensitive name.
*
* @param string $name Case-insensitive header field name.
* @return bool Returns true if any header names match the given header
* name using a case-insensitive string comparison. Returns false if
* no matching header name is found in the message.
*/
public function hasHeader( $name )
{
return $this->_checkMessageHeader( $name );
}
/**
* Retrieves a message header value by the given case-insensitive name.
*
* This method returns an array of all the header values of the given
* case-insensitive header name.
*
* If the header does not appear in the message, this method MUST return an
* empty array.
*
* @param string $name Case-insensitive header field name.
* @return string[] An array of string values as provided for the given
* header. If the header does not appear in the message, this method MUST
* return an empty array.
*/
public function getHeader( $name )
{
if ( !$this->_checkMessageHeader( $name ) )
{
return array();
}
$headers = $this->_getMessageHeaders();
foreach ( $headers as
$key =>
$header )
{
if ( strtolower( $name ) === strtolower( $key ) )
{
return $headers[$key];
}
}
}
/**
* Retrieves a comma-separated string of the values for a single header.
*
* This method returns all of the header values of the given
* case-insensitive header name as a string concatenated together using
* a comma.
*
* NOTE: Not all header values may be appropriately represented using
* comma concatenation. For such headers, use getHeader() instead
* and supply your own delimiter when concatenating.
*
* If the header does not appear in the message, this method MUST return
* an empty string.
*
* @param string $name Case-insensitive header field name.
* @return string A string of values as provided for the given header
* concatenated together using a comma. If the header does not appear in
* the message, this method MUST return an empty string.
*/
public function getHeaderLine( $name )
{
if ( !$this->_checkMessageHeader( $name ) )
{
return '';
}
return implode( ', ', $this->getHeader( $name ) );
}
/**
* Return an instance with the provided value replacing the specified header.
*
* While header names are case-insensitive, the casing of the header will
* be preserved by this function, and returned from getHeaders().
*
* 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 and/or updated header and value.
*
* @param string $name Case-insensitive header field name.
* @param string|string[] $value Header value(s).
* @return static
* @throws \InvalidArgumentException for invalid header names or values.
*/
public function withHeader( $name, $value )
{
$this->_validateMessageHeader( $name, $value );
$values = $this->_getMessageValues();
$values['headers'][$name] = $value;
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Return an instance with the specified header appended with the given value.
*
* Existing values for the specified header will be maintained. The new
* value(s) will be appended to the existing list. If the header did not
* exist previously, it will be added.
*
* 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 header and/or value.
*
* @param string $name Case-insensitive header field name to add.
* @param string|string[] $value Header value(s).
* @return static
* @throws \InvalidArgumentException for invalid header names.
* @throws \InvalidArgumentException for invalid header values.
*/
public function withAddedHeader( $name, $value )
{
$this->_validateMessageHeader( $name, $value );
$values = $this->_getMessageValues();
if ( $this->_checkMessageHeader( $name ) )
{
foreach ( $values['headers'] as
$key =>
$header )
{
if ( strtolower( $name ) === strtolower( $key ) )
{
if ( is_array( $value ) )
{
foreach ( $value as
$v )
{
$values['headers'][$key][] = $v;
}
} else
{
$values['headers'][$key][] = $value;
}
break;
}
}
} else
{
$values['headers'][$name] = is_array( $value )
? $value
: array(
$value );
}
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Return an instance without the specified header.
*
* Header resolution MUST be done without case-sensitivity.
*
* 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 named header.
*
* @param string $name Case-insensitive header field name to remove.
* @return static
*/
public function withoutHeader( $name )
{
$values = $this->_getMessageValues();
if ( $this->_checkMessageHeader( $name ) )
{
foreach ( $values['headers'] as
$key =>
$header )
{
if ( strtolower( $name ) === strtolower( $key ) )
{
unset( $values['headers'][$key] );
break;
}
}
}
return $this->_instantiateMessageNewInstance( $values );
}
/**
* Gets the body of the message.
*
* @return StreamInterface Returns the body as a stream.
*/
public function getBody()
{
$values = $this->_getMessageValues();
return new \oroboros\core\libraries\stream\Stream( $values['body'] );
}
/**
* Return an instance with the specified message body.
*
* The body MUST be a StreamInterface object.
*
* This method MUST be implemented in such a way as to retain the
* immutability of the message, and MUST return a new instance that has the
* new body stream.
*
* @param StreamInterface $body Body.
* @return static
* @throws \InvalidArgumentException When the body is not valid.
*/
public function withBody( \Psr\Http\Message\StreamInterface $body )
{
if ( !($body instanceof \Psr\Http\Message\StreamInterface) )
{
//cannot set an array as message body
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, '\\Psr\\Http\\Message\\StreamInterface',
is_object( $body )
? get_class( $body )
: gettype( $body ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
$values = $this->_getMessageValues();
$values['body'] = $body->detach();
return $this->_instantiateMessageNewInstance( $values );
}
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
* <Message 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 _initializeMessage( $body, $headers = null,
$protocol = null )
{
$this->_getMessageValidRequestHeaders();
$this->_getMessageValidResponseHeaders();
$this->_setMessageBody( $body );
if ( !is_null( $headers ) )
{
$this->_setMessageHeaders( $headers );
}
if ( is_null( $protocol ) )
{
$protocol = $this->_message_protocol_default;
}
$this->_setMessageProtocol( $protocol );
$this->_message_is_initialized = true;
}
/**
* Returns the correctly structured header array.
* @return array
*/
protected function _getMessageHeaders()
{
$headers = array();
foreach ( $this->_message_headers as
$header =>
$value )
{
$headers[$header] = $value->getValue();
}
return $headers;
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* Validates header parameters according to Psr-7 standards.
* @param string $name
* @param string|string[] $value
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
*/
private function _validateMessageHeader( $name, $value )
{
if ( !is_string( $name ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string', gettype( $name ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
} elseif ( !is_string( $value ) && !is_array( $value ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string|array', gettype( $value ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
}
/**
* Checks if the supplied header name exists in a case-insensitive way.
* @param string $name
* @return bool
*/
private function _checkMessageHeader( $name )
{
foreach ( array_keys( $this->_message_headers ) as
$header )
{
if ( strtolower( $name ) === strtolower( $header ) )
{
return true;
}
}
return false;
}
/**
* Initialization method to obtain the valid request headers
* from the dedicated enumerator.
*/
private function _getMessageValidRequestHeaders()
{
if ( empty( self::$_message_headers_valid['request'] ) )
{
self::$_message_headers_valid['request'] = \oroboros\core\libraries\enum\http\RequestHeaders::valid();
}
}
/**
* Initialization method to obtain the valid response headers
* from the dedicated enumerator.
*/
private function _getMessageValidResponseHeaders()
{
if ( empty( self::$_message_headers_valid['response'] ) )
{
self::$_message_headers_valid['response'] = \oroboros\core\libraries\enum\http\ResponseHeaders::valid();
}
}
/**
* Sets the headers passed into initialization as header objects,
* and sets an array of the names locally for reference.
* @param array $headers
*/
private function _setMessageHeaders( array $headers )
{
$objs = array();
foreach ( $headers as
$header =>
$value )
{
$objs[$header] = new \oroboros\core\utilities\http\Header( $header,
$value );
}
$this->_message_headers = $objs;
}
/**
* Sets the message body as a stream resource. Accepts an existing resource, and creates one if passed a scalar value.
* @param scalar|\Psr\Http\Message\StreamInterface $body
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid parameter type is passed (non-scalar, non-resource, not an instance of \Psr\Http\Message\StreamInterface )
*/
private function _setMessageBody( $body )
{
if ( is_array( $body ) )
{
//cannot set an array as message body
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__,
'resource|scalar|\\Psr\\Http\\Message\\StreamInterface|stringable object',
gettype( $body ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS
);
}
if ( is_object( $body ) && $body instanceof \Psr\Http\Message\StreamInterface )
{
//set the stream wrapper directly
$sth = $body->detach();
} else
{
//extract the content from the object and create a stream wrapper
$sth = fopen( 'php://temp', 'r+' );
fwrite( $sth, (string) $body );
}
$this->_initializeStream( $sth );
}
/**
* Creates an object representation of the http protocol
* @param string $protocol
* @return void
*/
private function _setMessageProtocol( $protocol )
{
$this->_message_protocol = new \oroboros\core\utilities\http\Protocol( $protocol );
}
/**
* Returns an array of the existing message values for this object,
* for substitution when returning instances that must retain object immutability.
* @return array
*/
private function _getMessageValues()
{
$values = array(
'body' => $this->_stream,
'headers' => $this->getHeaders(),
'protocol' => (string) $this->_message_protocol
);
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\stream\MessageTrait
*/
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'] );
return $instance;
}
}