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
<?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\file;
/**
* <Uploaded File Trait>
* Provides a set of methods to honor the Psr-7 Uploaded File Interface.
* --------
* 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\file\UploadedFileContract
* @satisfies \Psr\Http\Message\UploadedFileInterface
*/
trait UploadedFileTrait
{
/**
* Provides basic file handling functionality.
*/
use FileTrait;
/**
* Represents the subset of valid upload errors, as defined by PHP
* @var array
*/
private $_uploaded_file_valid_errors = array(
UPLOAD_ERR_OK,
UPLOAD_ERR_INI_SIZE,
UPLOAD_ERR_FORM_SIZE,
UPLOAD_ERR_PARTIAL,
UPLOAD_ERR_NO_FILE,
UPLOAD_ERR_NO_TMP_DIR,
UPLOAD_ERR_CANT_WRITE,
UPLOAD_ERR_EXTENSION
);
/**
* Represents the upload error, if an error occurs.
* If this has a value of 0, then no upload error occurred.
* @var int
*/
private $_uploaded_file_error = UPLOAD_ERR_OK;
/**
* Represents the uploaded file size.
* @var int
*/
private $_uploaded_file_size = 0;
/**
* Represents whether or not the current PHP execution is sapi or non-sapi
* @var bool
*/
private $_uploaded_file_is_sapi = false;
/**
* Represents the default stream wrapper class.
* @var string
*/
private $_uploaded_file_default_stream_wrapper = '\\oroboros\\core\\libraries\\stream\\Stream';
/**
* Represents the current stream wrapper class,
* which is the default, unless substituted.
* @var string
*/
private $_uploaded_file_stream_wrapper = '\\oroboros\\core\\libraries\\stream\\Stream';
/**
* -------------------------------------------------------------------------
* Contract Methods
*
* These methods satisfy the public api defined in the uploaded file contract
*
* @satisfies \oroboros\core\interfaces\contract\libraries\file\UploadedFileContract
* @satisfies \Psr\Http\Message\UploadedFileInterface
*
* -------------------------------------------------------------------------
*/
/**
* Returns a collection of UploadedFile objects from the full set of files passed in $_FILES
* @param array $files
* @return \oroboros\core\libraries\container\Collection
*/
public static function getUploadedFileCollection( $files )
{
return self::_parseUploadedFilesStatic( $files );
}
/**
* <Uploaded File Object Constructor>
* This constructor should receive as it's only parameter
* the value of a file upload within $_FILES
* @param array $uploaded_file
* @throws \oroboros\core\utilities\exception\RuntimeException If instantiation cannot complete with the provided parameters.
*/
public function __construct( $uploaded_file )
{
try
{
$this->_initializeUploadedFileObject( $uploaded_file );
} catch ( \Exception $e )
{
throw new \oroboros\core\utilities\exception\RuntimeException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_CORE_LIBRARY_FAILURE_MESSAGE,
get_class( $this ), $e->getMessage() ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_LIBRARY_FAILURE,
$e );
}
}
/**
* Retrieve a stream representing the uploaded file.
*
* This method MUST return a StreamInterface instance, representing the
* uploaded file. The purpose of this method is to allow utilizing native PHP
* stream functionality to manipulate the file upload, such as
* stream_copy_to_stream() (though the result will need to be decorated in a
* native PHP stream wrapper to work with such functions).
*
* If the moveTo() method has been called previously, this method MUST raise
* an exception.
*
* @return StreamInterface Stream representation of the uploaded file.
* @throws \RuntimeException in cases when no stream is available.
* @throws \RuntimeException in cases when no stream can be created.
*/
public function getStream()
{
if ( !$this->_fileExists() )
{
throw new \oroboros\core\utilities\exception\RuntimeException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_FILESYSTEM_MESSAGE,
__METHOD__,
$this->_getFileFullyQualifiedName() . ' does not exist at it\'s original location.' ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM
);
}
try
{
$resource = $this->_getFileStreamResource();
$stream = new $this->_uploaded_file_stream_wrapper( $resource );
return $stream;
} catch ( \Exception $e )
{
throw new \oroboros\core\utilities\exception\RuntimeException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_CORE_STREAM_FAILURE_MESSAGE,
$this->_uploaded_file_stream_wrapper, $e->getMessage() ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM, $e
);
}
}
/**
* Move the uploaded file to a new location.
*
* Use this method as an alternative to move_uploaded_file(). This method is
* guaranteed to work in both SAPI and non-SAPI environments.
* Implementations must determine which environment they are in, and use the
* appropriate method (move_uploaded_file(), rename(), or a stream
* operation) to perform the operation.
*
* $targetPath may be an absolute path, or a relative path. If it is a
* relative path, resolution should be the same as used by PHP's rename()
* function.
*
* The original file or stream MUST be removed on completion.
*
* If this method is called more than once, any subsequent calls MUST raise
* an exception.
*
* When used in an SAPI environment where $_FILES is populated, when writing
* files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
* used to ensure permissions and upload status are verified correctly.
*
* If you wish to move to a stream, use getStream(), as SAPI operations
* cannot guarantee writing to stream destinations.
*
* @see http://php.net/is_uploaded_file
* @see http://php.net/move_uploaded_file
* @param string $targetPath Path to which to move the uploaded file.
* @throws \InvalidArgumentException if the $targetPath specified is invalid.
* @throws \RuntimeException on any error during the move operation.
* @throws \RuntimeException on the second or subsequent call to the method.
*/
public function moveTo( $targetPath )
{
$exception = '\\oroboros\\core\\utilities\\exception\\RuntimeException';
$invalid_exception = '\\oroboros\\core\\utilities\\exception\\InvalidArgumentException';
$error = false;
$msg = \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_FILESYSTEM_MESSAGE;
$code = \oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM;
$invalid = false;
if ( !$this->_fileExists() )
{
$error = sprintf( $msg, __METHOD__,
$this->_getFileFullyQualifiedName() . ' does not exist at it\'s original location.' );
} elseif ( !$this->_fileReadable() )
{
$error = sprintf( $msg, __METHOD__,
$this->_getFileFullyQualifiedName() . ' is not readable.' );
} elseif ( !is_writeable( $targetPath ) )
{
$error = sprintf( $msg, __METHOD__,
$targetPath . ' is not writeable.' );
$invalid = true;
}
if ( $error )
{
$e = $invalid
? $invalid_exception
: $exception;
throw new $e( $error, $code );
}
$this->_moveUploadedFile( $targetPath );
}
/**
* Retrieve the file size.
*
* Implementations SHOULD return the value stored in the "size" key of
* the file in the $_FILES array if available, as PHP calculates this based
* on the actual size transmitted.
*
* @return int|null The file size in bytes or null if unknown.
*/
public function getSize()
{
return $this->_uploaded_file_size;
}
/**
* Retrieve the error associated with the uploaded file.
*
* The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
*
* If the file was uploaded successfully, this method MUST return
* UPLOAD_ERR_OK.
*
* Implementations SHOULD return the value stored in the "error" key of
* the file in the $_FILES array.
*
* @see http://php.net/manual/en/features.file-upload.errors.php
* @return int One of PHP's UPLOAD_ERR_XXX constants.
*/
public function getError()
{
if ( in_array( $this->_uploaded_file_error,
$this->_uploaded_file_valid_errors ) )
{
return $this->_uploaded_file_error;
}
//If no error was supplied,
//the file uploaded ok.
return UPLOAD_ERR_OK;
}
/**
* Retrieve the filename sent by the client.
*
* Do not trust the value returned by this method. A client could send
* a malicious filename with the intention to corrupt or hack your
* application.
*
* Implementations SHOULD return the value stored in the "name" key of
* the file in the $_FILES array.
*
* @return string|null The filename sent by the client or null if none
* was provided.
*/
public function getClientFilename()
{
//The alias is stored using the FileTrait as it's alias.
$alias = $this->_getFileAlias();
return $alias
? $alias
: null;
}
/**
* Retrieve the media type sent by the client.
*
* Do not trust the value returned by this method. A client could send
* a malicious media type with the intention to corrupt or hack your
* application.
*
* Implementations SHOULD return the value stored in the "type" key of
* the file in the $_FILES array.
*
* @return string|null The media type sent by the client or null if none
* was provided.
*/
public function getClientMediaType()
{
//Mime Type is stored using FileTrait, and obtained
//using a codex lookup if it is not explicitly passed.
//
//In the case where a wonky, possibly incompatible mime type is passed,
//this will correct it to the known universalized RFC mime type.
//
//Psr standards indicate that you should return the passed mime type,
//but do not explicitly exclude using the universal RFC standard
//when applicable.
return $this->_getFileMimeType();
}
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
*
* @param array $uploaded_file
*/
protected function _initializeUploadedFileObject( $uploaded_file )
{
$errors = array();
if ( !is_array( $errors ) )
{
$errors[] = '[$uploaded_file] must be an array';
}
if ( !empty( $errors ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_CORE_LIBRARY_FAILURE_MESSAGE,
get_class( $this ), implode( ', ', $errors ) ),
\oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_CORE_LIBRARY_FAILURE );
}
$file = ( isset( $uploaded_file['tmp_name'] )
? $uploaded_file['tmp_name']
: false);
$type = ( isset( $uploaded_file['type'] )
? $uploaded_file['type']
: null);
$temp_alias = ( isset( $uploaded_file['name'] )
? $uploaded_file['name']
: null);
$this->_uploaded_file_error = (isset( $uploaded_file['error'] )
? $uploaded_file['error']
: UPLOAD_ERR_OK);
$this->_uploaded_file_size = ( isset( $uploaded_file['size'] )
?: filesize( $file ) );
$this->_initializeFileObject( $file, $type, $temp_alias );
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* Handles the safe move operation, regardless of whether
* it is an http or cli environment.
* @param type $filePath The new location for the file
* @throws \oroboros\core\utilities\exception\RuntimeException on any error during the move operation
*/
private function _moveUploadedFile( $filePath )
{
$exception = '\\oroboros\\core\\utilities\\exception\\RuntimeException';
try
{
$old = $this->_getFileFullyQualifiedName();
$new = realpath( $filePath ) . DIRECTORY_SEPARATOR . $this->_getFileAlias();
if ( \oroboros\core\interfaces\enumerated\environment\CgiEnvironmentApi::IS_CLI )
{
$this->_moveUploadedCliFile( $old, $new );
} else
{
$this->_moveUploadedHttpFile( $old, $new );
}
} catch ( \Exception $e )
{
throw new \oroboros\core\utilities\exception\RuntimeException(
$e->getMessage(), $e->getCode(), $e );
}
}
/**
* Moves the file in a http-safe way.
* @param type $old the file upload
* @param type $new the new location for the file
* @throws \oroboros\core\utilities\exception\RuntimeException if the supplied file is not an uploaded file.
*/
private function _moveUploadedHttpFile( $old, $new )
{
if ( !is_uploaded_file( $old ) )
{
throw new $exception(
sprintf( '%s is not a valid uploaded file.', $old ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_FILESYSTEM
);
}
move_uploaded_file( $old, $new );
$this->_file_exists = false;
}
/**
* Moves the file in a cli-safe way.
* @param string $old The location of the existing file
* @param string $new The new location
*/
private function _moveUploadedCliFile( $old, $new )
{
rename( $old, $new );
$this->_file_exists = false;
}
/**
* Corrects known edge-cases in the $_FILES superglobal
* structure that can be corrected through rekeying the array.
* @param array $files the raw $_FILES array
* @return type \oroboros\core\libraries\container\Collection
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if an invalid $_FILES array is passed.
*/
private static function _parseUploadedFilesStatic( $files )
{
if ( !is_array( $files ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( 'Provided [$files] is not an array.' ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
if ( self::_validateUploadedFileArray( $files ) )
{
//this takes care of a direct file array that does not need a collection.
//a new instance of the called class implementing this trait will be returned.
return self::_createUploadedFileInstance( $files );
}
$file_collection = new \oroboros\core\libraries\container\Collection();
foreach ( $files as
$file_key =>
$fileset )
{
if ( self::_validateUploadedFileArray( $fileset ) )
{
//this is a single-leaf file array.
$file_collection[$file_key] = self::_createUploadedFileInstance( $fileset );
continue;
} elseif ( self::_isMultileafUploadedFileArray( $fileset ) )
{
//this is an unparsed multi-leaf file array.
$path = self::_getUploadedFileMultileafPathString( $fileset['name'] );
$tmp_collection = new \oroboros\core\libraries\container\Collection ( );
foreach ( array(
'name',
'type',
'size',
'tmp_name',
'error' ) as
$expected_key )
{
$tmp_collection[$path . '.' . $expected_key] = self::_extractUploadedFileLeafKeys( $fileset[$expected_key] );
}
foreach ( self::_reorderUploadedFileMultileafArray( $tmp_collection->get( $path ) ) as
$numeric_file_key =>
$numeric_file_array )
{
$file_collection[$file_key . '.' . $path . '.' . $numeric_file_key] = self::_createUploadedFileInstance( $numeric_file_array );
}
continue;
} elseif ( self::_checkUploadedFileLeafKeysAlreadyHandled( $fileset ) ||
$fileset instanceof \Psr\Http\Message\UploadedFileInterface )
{
//Already contains correct objects. We can pass this key with no further work.
//This should cover all cases of reinstantiation to honor Psr-7 immutability.
$file_collection[$file_key] = $fileset;
continue;
} else
{
//Unparseable elements exist. Fail it.
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( 'Provided [$files] is not a valid file array.' ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
}
return $file_collection;
}
/**
* Returns a boolean determination as to whether a provided array
* can be directly used to create a valid UploadedFile instance.
* @param array $files
* @return bool
*/
private static function _validateUploadedFileArray( $files )
{
if ( !is_array( $files ) )
{
return false;
}
return ( array_key_exists( 'name', $files ) && !is_array( $files['name'] )
&& array_key_exists( 'type', $files ) && !is_array( $files['type'] )
&& array_key_exists( 'size', $files ) && !is_array( $files['size'] )
&& array_key_exists( 'tmp_name', $files ) && !is_array( $files['tmp_name'] )
&& array_key_exists( 'error', $files ) && !is_array( $files['error'] )
);
}
/**
* Returns a boolean determination as to whether the provided array is a multi-leaf
* file array that needs additional consideration.
* @param array $files
* @return bool
*/
private static function _isMultileafUploadedFileArray( $files )
{
if ( !is_array( $files ) )
{
return false;
}
return ( array_key_exists( 'name', $files ) && is_array( $files['name'] )
&& array_key_exists( 'type', $files ) && is_array( $files['type'] )
&& array_key_exists( 'size', $files ) && is_array( $files['size'] )
&& array_key_exists( 'tmp_name', $files ) && is_array( $files['tmp_name'] )
&& array_key_exists( 'error', $files ) && is_array( $files['error'] )
);
}
/**
* Creates an instance of the called class implementing this trait.
* This class must also implement \Psr\Http\Message\UploadedFileInterface,
* and it must either use the provided constructor or have one that is compatible
* with the one provided by this trait.
*
* @param type $files
* @return \Psr\Http\Message\UploadedFileInterface (this will be an instance of the called class that directly or indirectly implements this trait, on the assumption that the constructor exists as provided in this trait, or is compatible with it).
* @throws \oroboros\core\utilities\exception\LogicException The implementing class must be an instance of \Psr\Http\Message\UploadedFileInterface
*/
private static function _createUploadedFileInstance( $files )
{
$interface = 'Psr\\Http\\Message\\UploadedFileInterface';
if ( !in_array( $interface, class_implements( get_called_class() ) ) )
{
throw new \oroboros\core\utilities\exception\LogicException(
sprintf( 'Logic error at [%s]: implementing class [%s] must be an instance of [%s].',
__METHOD__, get_called_class(), $interface ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_CORE_LIBRARY_FAILURE
);
}
$class = '\\' . get_called_class();
return new $class( $files );
}
/**
* Contencates the multidimensional array structure
* into a collection compatible dot separated notation string.
* This allows this class to easily fix miskeyed $_FILES keys for
* multipart uploads without a ton of redundant recursion.
* @param array $subject The nested files array, typically a multi-part expression of $_FILES
* @param string $path (optional) This is used for recursion and should not be provided. If it is provided, it will act as a prefix to the filepath.
* @return string
*/
private static function _getUploadedFileMultileafPathString( $subject,
$path = null )
{
if ( !is_array( $subject ) )
{
return $path;
}
foreach ( $subject as
$key =>
$value )
{
if ( is_int( $key ) && !is_array( $value ) )
{
//we have reached the leaf, do not include the leaf numeric key.
return $path;
}
$path = ( is_null( $path )
? null
: $path . '.') . $key;
return self::_getUploadedFileMultileafPathString( $value, $path );
}
}
/**
* Returns the numeric leaf keys of a multidimensional array,
* ignoring the rest of the nested keys.
* @param array $subject
* @return array
*/
private static function _extractUploadedFileLeafKeys( $subject )
{
if ( !is_array( $subject ) )
{
return false;
}
foreach ( $subject as
$key =>
$value )
{
if ( !is_array( $value ) )
{
return $subject;
}
return self::_extractUploadedFileLeafKeys( $value );
}
}
/**
* Checks if nested leaf keys are already
* instances of \Psr\Http\Message\FileUploadInterface
* @param array $subject
* @return bool
*/
private static function _checkUploadedFileLeafKeysAlreadyHandled( $subject )
{
if ( !is_array( $subject )
&& !( is_array( $subject ) && empty( $subject ) )
&& !( is_object( $subject ) && ( $subject instanceof \Psr\Http\Message\FileUploadInterface ) ) )
{
//Not valid
return false;
}
if ( is_array( $subject && count( $subject ) === 1 ) )
{
$s = array_shift( $subject );
return self::_checkUploadedFileLeafKeysAlreadyHandled( $s );
}
foreach ( $subject as
$sub )
{
if ( !self::_checkUploadedFileLeafKeys( $sub ) )
{
return false;
}
}
return true;
}
/**
* Checks all valid cases for nesting of ambiguous multi-leaf file arrays.
* @param mixed $subject
* @return bool
*/
private static function _checkUploadedFileLeafKeys( $subject )
{
//Rules out cases that are not an array or instance of an uploaded file instance
if ( !is_array( $subject )
&& !(is_object( $subject ) && ($subject instanceof \Psr\Http\Message\UploadedFileInterface) ) )
{
return false;
}
//Accepts cases that are a valid and correctly keyed uploaded file array
elseif ( is_array( $subject ) && self::_validateUploadedFileArray( $subject ) )
{
return true;
}
//Handles nested arrays
elseif ( is_array( $subject ) )
{
foreach ( $subject as
$value )
{
//Covers acceptable nested array cases
if ( self::_validateUploadedFileArray( $value ) || ( is_object( $value )
&& ( $value instanceof \Psr\Http\Message\UploadedFileInterface ) )
|| ( self::_checkUploadedFileLeafKeys( $value ) ) )
{
continue;
}
//if any fail condition is encountered, all of it fails.
return false;
}
}
//If no fail condition was encountered, it passes.
return true;
}
/**
* Corrects the issue of the leaf keys of a multi-leaf file array being
* numeric instead of the expected keys from $_FILES
* @param array $subject Takes an array of arrays, where the keys are expected keys from $_FILES and the subkeys are integers
* @return array
*/
private static function _reorderUploadedFileMultileafArray( array $subject )
{
$corrected_array = array();
$count = count( $subject['error'] );
$keys = array_keys( $subject['error'] );
foreach ( array(
'name',
'type',
'size',
'tmp_name',
'error' ) as
$expected_key )
{
for ( $i = 0;
$i < $count;
$i++ )
{
$corrected_array[$keys[$i]][$expected_key] = $subject[$expected_key][$keys[$i]];
}
}
return $corrected_array;
}
}