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
<?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;
/**
* <Stream Trait>
* Provides a set of methods to represent a Psr-7 stream.
*
* NOTE: Most of this was ported from a prior build.
* Method documentation and some stability refactoring will be added
* throughout the alpha and beta phase of Oroboros core for code ported
* from legacy builds.
* --------
* 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\stream\StreamContract
* @satisfies \Psr\Http\Message\StreamInterface
*/
trait StreamTrait
{
private $_purge_file_on_destruct = false;
private $_cache_file;
private $_stream;
private $_readable;
private $_writeable;
private $_seekable;
private $_size;
private $_uri;
private $_meta;
private $_offset = 0;
/**
* -------------------------------------------------------------------------
* Contract Methods
*
* These methods satisfy the public api defined in the stream contract
*
* @satisfies \oroboros\core\interfaces\contract\libraries\stream\StreamContract
*
* -------------------------------------------------------------------------
*/
/**
* <Stream Constructor>
* Creates a new instance of a stream wrapper.
* @param resource $body
*/
public function __construct( $body )
{
$this->_initializeStream( $body );
}
/**
* <Stream Destructor>
* Destroys any cache files that may exist.
* A fallback shutdown function is also declared as a redundancy,
* in the event of a fatal error that prevents the destructor from firing.
*/
public function __destruct()
{
if ( $this->_purge_file_on_destruct )
{
$file = $this->_cache_file;
if ( file_exists( $file ) )
{
unlink( $file );
}
}
}
/**
* Reads all data from the stream into a string, from the beginning to end.
*
* This method MUST attempt to seek to the beginning of the stream before
* reading data and read the stream until the end is reached.
*
* Warning: This could attempt to load a large amount of data into memory.
*
* This method MUST NOT raise an exception in order to conform with PHP's
* string casting operations.
*
* @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
* @return string
*/
public function __toString()
{
try
{
$this->rewind();
$string = $this->read( $this->getSize() );
return $string;
} catch ( \Exception $e )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::ERROR,
'Unable to cast stream to string at: ' . __LINE__ . ' of ' . __METHOD__ . PHP_EOL . 'Original exception: ' . $e->getMessage() );
//this will cause an error, but the log will reveal the issue if it is enabled.
return false;
}
}
/**
* Seek to the beginning of the stream.
*
* If the stream is not seekable, this method will raise an exception;
* otherwise, it will perform a seek(0).
*
* @see seek()
* @see http://www.php.net/manual/en/function.fseek.php
* @throws \RuntimeException on failure.
*/
public function rewind()
{
if ( !$this->isSeekable() )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream is not seekable: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException( 'Stream is not seekable. Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_SERVICE_FAILURE );
}
$this->seek( 0 );
}
/**
* Read data from the stream.
*
* @param int $length Read up to $length bytes from the object and return
* them. Fewer than $length bytes may be returned if underlying stream
* call returns fewer bytes.
* @return string Returns the data read from the stream, or an empty string
* if no bytes are available.
* @throws \RuntimeException if an error occurs.
*/
public function read( $length )
{
if ( !$this->isReadable() )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream is not readable: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException( 'Stream is not readable. '
. 'Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM );
}
if ( !is_int( $length ) || $length < 0 )
{
throw new \RuntimeException(
'Invalid paramters passed at: '
. __LINE__ . ' of ' . __METHOD__
. '. Expected integer, 0 or greater.',
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$output = "";
$start = $this->tell();
try
{
while ( !$this->eof() && ($this->tell() - $start) < $length )
{
$output .= fread( $this->_stream, 1 );
$this->_offset++;
}
} catch ( Exception $e )
{
throw new \RuntimeException(
'Operation failed with error: '
. $e->getMessage() . PHP_EOL
. 'Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_STREAM_FAILURE,
$e );
}
return $output;
}
/**
* Separates any underlying resources from the stream.
*
* After the stream has been detached, the stream is in an unusable state.
*
* @return resource|null Underlying PHP stream, if any
*/
public function detach()
{
if ( !isset( $this->_stream ) )
{
return null;
}
$result = $this->_stream;
$this->_stream = null;
$this->_size = $this->_uri = null;
$this->_readable = $this->_writable = $this->_seekable = false;
return $result;
}
/**
* Write data to the stream.
*
* @param string $string The string that is to be written.
* @return int Returns the number of bytes written to the stream.
* @throws \RuntimeException on failure.
*/
public function write( $string )
{
if ( !$this->isWritable() )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream is not writeable at: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException( 'Stream is not writeable. Thrown at: '
. __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM );
}
if ( !is_string( $string ) )
{
try
{
$string = (string) $string;
} catch ( \Exception $e )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream is not writeable at: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException(
'Provided parameter is not a valid string, '
. 'and could not be cast to string. Thrown at: '
. __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS,
$e );
}
}
$strlen = strlen( $string );
$tmp_pointer = 0;
if ( $strlen === 0 )
{
return $strlen;
}
try
{
while ( $tmp_pointer < $strlen )
{
fwrite( $this->_stream, substr( $string, $tmp_pointer, 1 ) );
$this->_size++;
$tmp_pointer++;
}
} catch ( \Exception $e )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream write failed at: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException(
"Stream write failed with an error: " . $e->getMessage()
. PHP_EOL . 'Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_STREAM_FAILURE,
$e );
}
return $tmp_pointer;
}
/**
* Closes the stream and any underlying resources.
*
* @return void
*/
public function close()
{
fclose( $this->_stream );
}
/**
* Returns the current position of the file read/write pointer
*
* @return int Position of the file pointer
* @throws \RuntimeException on error.
*/
public function tell()
{
return $this->_offset;
}
/**
* Get stream metadata as an associative array or retrieve a specific key.
*
* The keys returned are identical to the keys returned from PHP's
* stream_get_meta_data() function.
*
* @see http://php.net/manual/en/function.stream-get-meta-data.php
* @param string $key Specific metadata to retrieve.
* @return array|mixed|null Returns an associative array if no key is
* provided. Returns a specific key value if a key is provided and the
* value is found, or null if the key is not found.
*/
public function getMetadata( $key = null )
{
return $this->_meta;
}
/**
* Returns whether or not the stream is readable.
*
* @return bool
*/
public function isReadable()
{
return $this->_readable;
}
/**
* Returns the remaining contents in a string
*
* @return string
* @throws \RuntimeException if unable to read.
* @throws \RuntimeException if error occurs while reading.
*/
public function getContents()
{
$output = "";
$length = $this->getSize() - $this->tell();
try
{
return $this->read( $length );
} catch ( \Exception $e )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::WARNING,
'Stream contents not available at: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \RuntimeException(
"Unable to get remaining stream contents due to an error: "
. $e->getMessage() . PHP_EOL . 'Thrown at: '
. __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_STREAM_FAILURE,
$e );
}
}
/**
* Seek to a position in the stream.
*
* @see http://www.php.net/manual/en/function.fseek.php
* @param int $offset Stream offset
* @param int $whence Specifies how the cursor position will be calculated
* based on the seek offset. Valid values are identical to the built-in
* PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
* offset bytes SEEK_CUR: Set position to current location plus offset
* SEEK_END: Set position to end-of-stream plus offset.
* @throws \RuntimeException on failure.
*/
public function seek( $offset, $whence = SEEK_SET )
{
if ( !$this->isSeekable() )
{
throw new \RuntimeException( 'Stream is not seekable. Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_STREAM_FAILURE );
}
try
{
fseek( $this->_stream, $offset, $whence );
$this->_offset = $offset;
} catch ( Exception $e )
{
throw new \RuntimeException( $e->getMessage(),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_STREAM_FAILURE,
$e );
}
}
/**
* Returns whether or not the stream is seekable.
*
* @return bool
*/
public function isSeekable()
{
return $this->_seekable;
}
/**
* Get the size of the stream if known.
*
* @return int|null Returns the size in bytes if known, or null if unknown.
*/
public function getSize()
{
return $this->_size;
}
/**
* Returns true if the stream is at the end of the stream.
*
* @return bool
*/
public function eof()
{
return (($this->_offset === $this->_size)
? true
: false);
}
/**
* Returns whether or not the stream is writable.
*
* @return bool
*/
public function isWritable()
{
return $this->_writeable;
}
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
* <Stream Initialization>
* Initializes the stream wrapper.
* @param resource $stream
* @throws \oroboros\core\utilities\exception\Exception
*/
protected function _initializeStream( $stream )
{
if ( !is_resource( $stream ) || !(get_resource_type( $stream ) === 'stream') )
{
throw new \oroboros\core\utilities\exception\Exception(
'Provided stream must be a resource of type: [stream]. '
. 'Thrown at: ' . __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$this->_stream = $stream;
$this->_meta = stream_get_meta_data( $this->_stream );
$this->_readable = strpos( $this->_meta['mode'], 'r' ) !== false
|| strpos( $this->_meta['mode'], '+' ) !== false;
$this->_writeable = strpos( $this->_meta['mode'], 'w' ) !== false
|| strpos( $this->_meta['mode'], 'r+' ) !== false
|| strpos( $this->_meta['mode'], 'x' ) !== false
|| strpos( $this->_meta['mode'], 'a' ) !== false;
$this->_seekable = (array_key_exists( 'seekable', $this->_meta )
? $this->_meta['seekable']
: false);
$this->_uri = $this->_meta['uri'];
$this->_offset = ftell( $this->_stream );
$fstat = fstat( $this->_stream );
$this->_size = ($fstat && array_key_exists( 'size', $fstat )
? $fstat['size']
: null);
if ( !$fstat || !$this->_writeable || in_array( $this->_meta['uri'],
array(
'php://temp',
'php://memory',
'php://input',
) ) || strpos( $this->_meta['uri'], 'php://temp/maxmemory:' ) !== false )
{
//create a writeable cache file if the stream is in memory or temp, so we can manipulate it further
$this->_createCacheStreamFile();
}
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* Creates a cache stream file, in the event that the
* passed stream represents a resource that cannot be reused.
* @throws \oroboros\core\utilities\exception\Exception if the cache directory is not writeable
*/
private function _createCacheStreamFile()
{
$file = OROBOROS_CACHE . $this->_createStreamCacheFileName();
if ( !is_writable( dirname( $file ) ) )
{
\oroboros\Oroboros::log( \Psr\Log\LogLevel::ERROR,
'Cache direcory: [' . OROBOROS_CACHE . '] is not writeable at: ' . __LINE__ . ' of ' . __METHOD__ );
throw new \oroboros\core\utilities\exception\Exception(
'Cache directory is not writeable! Thrown at: '
. __LINE__ . ' of ' . __METHOD__,
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM );
}
$this->_purge_file_on_destruct = true;
$this->_cache_file = $file;
//fallback cleanup, in the event that execution does not close clean.
register_shutdown_function( function() use ( $file )
{
if ( file_exists( $file ) )
{
unlink( $file );
}
} );
$newStream = fopen( $this->_cache_file, 'w+b' );
$oldOffset = $this->tell();
$this->rewind();
stream_copy_to_stream( $this->_stream, $newStream );
fclose( $this->_stream );
$this->_stream = $newStream;
$this->seek( $oldOffset );
$this->_initializeStream( $this->_stream );
}
/**
* Creates a non-colliding cache name,
* based off of the values in the cache directory.
* @return string
*/
private function _createStreamCacheFileName()
{
do
{
$time = \time();
$class = \get_class( $this );
$rand = (string) \mt_rand( 0, \mt_getrandmax() );
$cachename = \sha1( $class . $time . $rand ) . '.cache';
} while ( file_exists( OROBOROS_CACHE . $cachename ) && OROBOROS_CACHE );
return $cachename;
}
}