-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathImage.php
More file actions
78 lines (65 loc) · 2.32 KB
/
Image.php
File metadata and controls
78 lines (65 loc) · 2.32 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Sirius\Validation\Rule\Upload;
use Sirius\Validation\ErrorMessage;
use Sirius\Validation\Rule\AbstractRule;
class Image extends AbstractRule
{
const OPTION_ALLOWED_IMAGES = 'allowed';
const MESSAGE = 'The file is not a valid image (only {image_types} are allowed)';
const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)';
protected array $options = [
self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif']
];
/**
* @var array<int, string>
*/
protected $imageTypesMap = [
IMAGETYPE_GIF => 'gif',
IMAGETYPE_JPEG => 'jpg',
IMAGETYPE_JPEG2000 => 'jpg',
IMAGETYPE_PNG => 'png',
IMAGETYPE_PSD => 'psd',
IMAGETYPE_BMP => 'bmp',
IMAGETYPE_ICO => 'ico',
IMAGETYPE_WEBP => 'webp',
];
public function setOption(string $name, mixed $value): static
{
if ($name == self::OPTION_ALLOWED_IMAGES) {
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 {
$imageInfo = getimagesize($value['tmp_name']);
if (!is_array($imageInfo)) {
$this->success = false;
} else {
$extension = $this->imageTypesMap[$imageInfo[2]] ?? false;
$this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES]));
}
}
return $this->success;
}
public function getPotentialMessage(): ErrorMessage
{
$message = parent::getPotentialMessage();
$imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]);
$message->setVariables([
'image_types' => implode(', ', $imageTypes)
]);
return $message;
}
}