1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Sirius\Validation\Rule\Upload; |
5
|
|
|
|
6
|
|
|
use Sirius\Validation\Rule\AbstractRule; |
7
|
|
|
|
8
|
|
|
class Extension extends AbstractRule |
9
|
|
|
{ |
10
|
|
|
const OPTION_ALLOWED_EXTENSIONS = 'allowed'; |
11
|
|
|
|
12
|
|
|
const MESSAGE = 'The file does not have an acceptable extension ({file_extensions})'; |
13
|
|
|
|
14
|
|
|
const LABELED_MESSAGE = '{label} does not have an acceptable extension ({file_extensions})'; |
15
|
|
|
|
16
|
|
|
protected $options = [ |
17
|
|
|
self::OPTION_ALLOWED_EXTENSIONS => [] |
18
|
|
|
]; |
19
|
|
|
|
20
|
4 |
|
public function setOption($name, $value) |
21
|
|
|
{ |
22
|
4 |
|
if ($name == self::OPTION_ALLOWED_EXTENSIONS) { |
23
|
4 |
|
if (is_string($value)) { |
24
|
1 |
|
$value = explode(',', $value); |
25
|
|
|
} |
26
|
4 |
|
$value = array_map('trim', $value); |
27
|
4 |
|
$value = array_map('strtolower', $value); |
28
|
|
|
} |
29
|
|
|
|
30
|
4 |
|
return parent::setOption($name, $value); |
31
|
|
|
} |
32
|
|
|
|
33
|
4 |
|
public function validate($value, string $valueIdentifier = null) |
34
|
|
|
{ |
35
|
4 |
|
$this->value = $value; |
36
|
4 |
|
if (! is_array($value) || ! isset($value['tmp_name'])) { |
37
|
|
|
$this->success = false; |
38
|
4 |
|
} elseif (! file_exists($value['tmp_name'])) { |
39
|
2 |
|
$this->success = $value['error'] === UPLOAD_ERR_NO_FILE; |
40
|
|
|
} else { |
41
|
2 |
|
$extension = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10)); |
42
|
2 |
|
$this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array( |
43
|
2 |
|
$extension, |
44
|
2 |
|
$this->options[self::OPTION_ALLOWED_EXTENSIONS] |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
4 |
|
return $this->success; |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
public function getPotentialMessage() |
52
|
|
|
{ |
53
|
1 |
|
$message = parent::getPotentialMessage(); |
54
|
1 |
|
$fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]); |
55
|
1 |
|
$message->setVariables([ |
56
|
1 |
|
'file_extensions' => implode(', ', $fileExtensions) |
57
|
|
|
]); |
58
|
|
|
|
59
|
1 |
|
return $message; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|