| 1 |
<?php |
| 2 |
|
| 3 |
namespace Rakit\Validation\Rules; |
| 4 |
|
| 5 |
use Rakit\Validation\Helper; |
| 6 |
use Rakit\Validation\MimeTypeGuesser; |
| 7 |
use Rakit\Validation\Rule; |
| 8 |
|
| 9 |
class Mimes extends Rule |
| 10 |
{ |
| 11 |
use Traits\FileTrait; |
| 12 |
|
| 13 |
/** @var string */ |
| 14 |
protected $message = "The :attribute file type must be :allowed_types"; |
| 15 |
|
| 16 |
/** @var string|int */ |
| 17 |
protected $maxSize = null; |
| 18 |
|
| 19 |
/** @var string|int */ |
| 20 |
protected $minSize = null; |
| 21 |
|
| 22 |
/** @var array */ |
| 23 |
protected $allowedTypes = []; |
| 24 |
|
| 25 |
/** |
| 26 |
* Given $params and assign $this->params |
| 27 |
* |
| 28 |
* @param array $params |
| 29 |
* @return self |
| 30 |
*/ |
| 31 |
public function fillParameters(array $params): Rule |
| 32 |
{ |
| 33 |
$this->allowTypes($params); |
| 34 |
return $this; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Given $types and assign $this->params |
| 39 |
* |
| 40 |
* @param mixed $types |
| 41 |
* @return self |
| 42 |
*/ |
| 43 |
public function allowTypes($types): Rule |
| 44 |
{ |
| 45 |
if (is_string($types)) { |
| 46 |
$types = explode('|', $types); |
| 47 |
} |
| 48 |
|
| 49 |
$this->params['allowed_types'] = $types; |
| 50 |
|
| 51 |
return $this; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Check the $value is valid |
| 56 |
* |
| 57 |
* @param mixed $value |
| 58 |
* @return bool |
| 59 |
*/ |
| 60 |
public function check($value): bool |
| 61 |
{ |
| 62 |
$allowedTypes = $this->parameter('allowed_types'); |
| 63 |
|
| 64 |
if ($allowedTypes) { |
| 65 |
$or = $this->validation ? $this->validation->getTranslation('or') : 'or'; |
| 66 |
$this->setParameterText('allowed_types', Helper::join(Helper::wraps($allowedTypes, "'"), ', ', ", {$or} ")); |
| 67 |
} |
| 68 |
|
| 69 |
// below is Required rule job |
| 70 |
if (!$this->isValueFromUploadedFiles($value) or $value['error'] == UPLOAD_ERR_NO_FILE) { |
| 71 |
return true; |
| 72 |
} |
| 73 |
|
| 74 |
if (!$this->isUploadedFile($value)) { |
| 75 |
return false; |
| 76 |
} |
| 77 |
|
| 78 |
// just make sure there is no error |
| 79 |
if ($value['error']) { |
| 80 |
return false; |
| 81 |
} |
| 82 |
|
| 83 |
if (!empty($allowedTypes)) { |
| 84 |
$guesser = new MimeTypeGuesser; |
| 85 |
$ext = $guesser->getExtension($value['type']); |
| 86 |
unset($guesser); |
| 87 |
|
| 88 |
if (!in_array($ext, $allowedTypes)) { |
| 89 |
return false; |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
return true; |
| 94 |
} |
| 95 |
} |
| 96 |
|