| 1 |
<?php |
| 2 |
|
| 3 |
namespace Rakit\Validation\Rules\Traits; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
|
| 7 |
trait SizeTrait |
| 8 |
{ |
| 9 |
|
| 10 |
/** |
| 11 |
* Get size (int) value from given $value |
| 12 |
* |
| 13 |
* @param int|string $value |
| 14 |
* @return float|false |
| 15 |
*/ |
| 16 |
protected function getValueSize($value) |
| 17 |
{ |
| 18 |
if ($this->getAttribute() |
| 19 |
&& ($this->getAttribute()->hasRule('numeric') || $this->getAttribute()->hasRule('integer')) |
| 20 |
&& is_numeric($value) |
| 21 |
) { |
| 22 |
$value = (float) $value; |
| 23 |
} |
| 24 |
|
| 25 |
if (is_int($value) || is_float($value)) { |
| 26 |
return (float) $value; |
| 27 |
} elseif (is_string($value)) { |
| 28 |
return (float) mb_strlen($value, 'UTF-8'); |
| 29 |
} elseif ($this->isUploadedFileValue($value)) { |
| 30 |
return (float) $value['size']; |
| 31 |
} elseif (is_array($value)) { |
| 32 |
return (float) count($value); |
| 33 |
} else { |
| 34 |
return false; |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Given $size and get the bytes |
| 40 |
* |
| 41 |
* @param string|int $size |
| 42 |
* @return float |
| 43 |
* @throws InvalidArgumentException |
| 44 |
*/ |
| 45 |
protected function getBytesSize($size) |
| 46 |
{ |
| 47 |
if (is_numeric($size)) { |
| 48 |
return (float) $size; |
| 49 |
} |
| 50 |
|
| 51 |
if (!is_string($size)) { |
| 52 |
throw new InvalidArgumentException("Size must be string or numeric Bytes", 1); |
| 53 |
} |
| 54 |
|
| 55 |
if (!preg_match("/^(?<number>((\d+)?\.)?\d+)(?<format>(B|K|M|G|T|P)B?)?$/i", $size, $match)) { |
| 56 |
throw new InvalidArgumentException("Size is not valid format", 1); |
| 57 |
} |
| 58 |
|
| 59 |
$number = (float) $match['number']; |
| 60 |
$format = isset($match['format']) ? $match['format'] : ''; |
| 61 |
|
| 62 |
switch (strtoupper($format)) { |
| 63 |
case "KB": |
| 64 |
case "K": |
| 65 |
return $number * 1024; |
| 66 |
|
| 67 |
case "MB": |
| 68 |
case "M": |
| 69 |
return $number * pow(1024, 2); |
| 70 |
|
| 71 |
case "GB": |
| 72 |
case "G": |
| 73 |
return $number * pow(1024, 3); |
| 74 |
|
| 75 |
case "TB": |
| 76 |
case "T": |
| 77 |
return $number * pow(1024, 4); |
| 78 |
|
| 79 |
case "PB": |
| 80 |
case "P": |
| 81 |
return $number * pow(1024, 5); |
| 82 |
|
| 83 |
default: |
| 84 |
return $number; |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Check whether value is from $_FILES |
| 90 |
* |
| 91 |
* @param mixed $value |
| 92 |
* @return bool |
| 93 |
*/ |
| 94 |
public function isUploadedFileValue($value): bool |
| 95 |
{ |
| 96 |
if (!is_array($value)) { |
| 97 |
return false; |
| 98 |
} |
| 99 |
|
| 100 |
$keys = ['name', 'type', 'tmp_name', 'size', 'error']; |
| 101 |
foreach ($keys as $key) { |
| 102 |
if (!array_key_exists($key, $value)) { |
| 103 |
return false; |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
return true; |
| 108 |
} |
| 109 |
} |
| 110 |
|