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