Refactor validation for withUploadedFiles

This commit is contained in:
PJ Dietz 2015-05-02 13:46:32 -04:00
parent 81055c3bd9
commit f98ee59e4a
2 changed files with 21 additions and 22 deletions

View File

@ -485,48 +485,44 @@ class ServerRequest extends Request implements ServerRequestInterface
}
/**
* @param array $uploadedFiles
* @param array $root
* @return bool
*/
private function isValidUploadedFilesTree(array $uploadedFiles)
private function isValidUploadedFilesTree(array $root)
{
// Allow empty array.
if (count($uploadedFiles) === 0) {
if (count($root) === 0) {
return true;
}
// All keys MUST be strings.
$keys = array_keys($uploadedFiles);
// If not empty, the array MUST have all string keys.
$keys = array_keys($root);
if (count($keys) !== count(array_filter($keys, "is_string"))) {
return false;
}
foreach ($uploadedFiles as $branch) {
// Valid if each child branch is valid.
foreach ($root as $branch) {
if (!$this->isValidUploadedFilesBranch($branch)) {
return false;
}
}
return true;
}
private function isValidUploadedFilesBranch($branch)
{
if ($branch instanceof UploadedFileInterface) {
return true;
}
if (!is_array($branch)) {
return false;
}
$values = array_values($branch);
foreach ($values as $value) {
if (!$this->isValidUploadedFilesBranch($value)) {
return false;
if (is_array($branch)) {
// Branch.
foreach ($branch as $child) {
if (!$this->isValidUploadedFilesBranch($child)) {
return false;
}
}
return true;
} else {
// Leaf. Valid only if this is an UploadedFileInterface.
return $branch instanceof UploadedFileInterface;
}
return true;
}
}

View File

@ -447,6 +447,7 @@ class ServerRequestTest extends \PHPUnit_Framework_TestCase
/**
* @covers ::withUploadedFiles
* @covers ::isValidUploadedFilesTree
* @covers ::isValidUploadedFilesBranch
* @expectedException \InvalidArgumentException
* @dataProvider invalidUploadedFilesProvider
*/
@ -481,7 +482,9 @@ class ServerRequestTest extends \PHPUnit_Framework_TestCase
"error" => UPLOAD_ERR_OK,
"size" => 1024
]
],
]
],
[
"nestedList" => [
"level2" => [
"name" => [