1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Sirius\Validation\Rule\Upload; |
5
|
|
|
|
6
|
|
|
use Sirius\Validation\Rule\AbstractRule; |
7
|
|
|
|
8
|
|
|
class Image extends AbstractRule |
9
|
|
|
{ |
10
|
|
|
const OPTION_ALLOWED_IMAGES = 'allowed'; |
11
|
|
|
|
12
|
|
|
const MESSAGE = 'The file is not a valid image (only {image_types} are allowed)'; |
13
|
|
|
|
14
|
|
|
const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)'; |
15
|
|
|
|
16
|
|
|
protected $options = [ |
17
|
|
|
self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif'] |
18
|
|
|
]; |
19
|
|
|
|
20
|
|
|
protected $imageTypesMap = [ |
21
|
|
|
IMAGETYPE_GIF => 'gif', |
22
|
|
|
IMAGETYPE_JPEG => 'jpg', |
23
|
|
|
IMAGETYPE_JPEG2000 => 'jpg', |
24
|
|
|
IMAGETYPE_PNG => 'png', |
25
|
|
|
IMAGETYPE_PSD => 'psd', |
26
|
|
|
IMAGETYPE_BMP => 'bmp', |
27
|
|
|
IMAGETYPE_ICO => 'ico', |
28
|
|
|
]; |
29
|
|
|
|
30
|
4 |
|
public function setOption($name, $value) |
31
|
|
|
{ |
32
|
4 |
|
if ($name == self::OPTION_ALLOWED_IMAGES) { |
33
|
4 |
|
if (is_string($value)) { |
34
|
1 |
|
$value = explode(',', $value); |
35
|
|
|
} |
36
|
4 |
|
$value = array_map('trim', $value); |
37
|
4 |
|
$value = array_map('strtolower', $value); |
38
|
|
|
} |
39
|
|
|
|
40
|
4 |
|
return parent::setOption($name, $value); |
41
|
|
|
} |
42
|
|
|
|
43
|
5 |
|
public function validate($value, string $valueIdentifier = null) |
44
|
|
|
{ |
45
|
5 |
|
$this->value = $value; |
46
|
5 |
|
if (! is_array($value) || ! isset($value['tmp_name'])) { |
47
|
|
|
$this->success = false; |
48
|
5 |
|
} elseif (! file_exists($value['tmp_name'])) { |
49
|
2 |
|
$this->success = $value['error'] === UPLOAD_ERR_NO_FILE; |
50
|
|
|
} else { |
51
|
3 |
|
$imageInfo = getimagesize($value['tmp_name']); |
52
|
3 |
|
if (!is_array($imageInfo)) { |
53
|
1 |
|
$this->success = false; |
54
|
|
|
} else { |
55
|
2 |
|
$extension = $this->imageTypesMap[$imageInfo[2]] ?? false; |
56
|
2 |
|
$this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES])); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
return $this->success; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
public function getPotentialMessage() |
64
|
|
|
{ |
65
|
1 |
|
$message = parent::getPotentialMessage(); |
66
|
1 |
|
$imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]); |
67
|
1 |
|
$message->setVariables([ |
68
|
1 |
|
'image_types' => implode(', ', $imageTypes) |
69
|
|
|
]); |
70
|
|
|
|
71
|
1 |
|
return $message; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|