| 1 |
<?php |
| 2 |
|
| 3 |
namespace Rakit\Validation\Rules\Traits; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Rakit\Validation\Helper; |
| 7 |
|
| 8 |
trait FileTrait |
| 9 |
{ |
| 10 |
|
| 11 |
/** |
| 12 |
* Check whether value is from $_FILES |
| 13 |
* |
| 14 |
* @param mixed $value |
| 15 |
* @return bool |
| 16 |
*/ |
| 17 |
public function isValueFromUploadedFiles($value): bool |
| 18 |
{ |
| 19 |
if (!is_array($value)) { |
| 20 |
return false; |
| 21 |
} |
| 22 |
|
| 23 |
$keys = ['name', 'type', 'tmp_name', 'size', 'error']; |
| 24 |
foreach ($keys as $key) { |
| 25 |
if (!array_key_exists($key, $value)) { |
| 26 |
return false; |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
return true; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Check the $value is uploaded file |
| 35 |
* |
| 36 |
* @param mixed $value |
| 37 |
* @return bool |
| 38 |
*/ |
| 39 |
public function isUploadedFile($value): bool |
| 40 |
{ |
| 41 |
return $this->isValueFromUploadedFiles($value) && is_uploaded_file($value['tmp_name']); |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Resolve uploaded file value |
| 46 |
* |
| 47 |
* @param mixed $value |
| 48 |
* @return array|null |
| 49 |
*/ |
| 50 |
public function resolveUploadedFileValue($value) |
| 51 |
{ |
| 52 |
if (!$this->isValueFromUploadedFiles($value)) { |
| 53 |
return null; |
| 54 |
} |
| 55 |
|
| 56 |
// Here $value should be an array: |
| 57 |
// [ |
| 58 |
// 'name' => string|array, |
| 59 |
// 'type' => string|array, |
| 60 |
// 'size' => int|array, |
| 61 |
// 'tmp_name' => string|array, |
| 62 |
// 'error' => string|array, |
| 63 |
// ] |
| 64 |
|
| 65 |
// Flatten $value to it's array dot format, |
| 66 |
// so our array must be something like: |
| 67 |
// ['name' => string, 'type' => string, 'size' => int, ...] |
| 68 |
// or for multiple values: |
| 69 |
// ['name.0' => string, 'name.1' => string, 'type.0' => string, 'type.1' => string, ...] |
| 70 |
// or for nested array: |
| 71 |
// ['name.foo.bar' => string, 'name.foo.baz' => string, 'type.foo.bar' => string, 'type.foo.baz' => string, ...] |
| 72 |
$arrayDots = Helper::arrayDot($value); |
| 73 |
|
| 74 |
$results = []; |
| 75 |
foreach ($arrayDots as $key => $val) { |
| 76 |
// Move first key to last key |
| 77 |
// name.foo.bar -> foo.bar.name |
| 78 |
$splits = explode(".", $key); |
| 79 |
$firstKey = array_shift($splits); |
| 80 |
$key = count($splits) ? implode(".", $splits) . ".{$firstKey}" : $firstKey; |
| 81 |
|
| 82 |
Helper::arraySet($results, $key, $val); |
| 83 |
} |
| 84 |
return $results; |
| 85 |
} |
| 86 |
} |
| 87 |
|