1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
namespace Sirius\Validation\Rule\File; |
4
|
|
|
|
5
|
|
|
use Sirius\Validation\Rule\AbstractRule; |
6
|
|
|
use Sirius\Validation\Util\RuleHelper; |
7
|
|
|
|
8
|
|
|
class ImageRatio extends AbstractRule |
9
|
|
|
{ |
10
|
|
|
// the image width/height ration; |
11
|
|
|
// can be a number or a string like 4:3, 16:9 |
12
|
|
|
const OPTION_RATIO = 'ratio'; |
13
|
|
|
// how much can the image ratio diverge from the allowed ratio |
14
|
|
|
const OPTION_ERROR_MARGIN = 'error_margin'; |
15
|
|
|
|
16
|
|
|
const MESSAGE = 'The image does must have a ratio (width/height) of {ratio})'; |
17
|
|
|
|
18
|
|
|
const LABELED_MESSAGE = '{label} does must have a ratio (width/height) of {ratio})'; |
19
|
|
|
|
20
|
|
|
protected $options = [ |
21
|
|
|
self::OPTION_RATIO => 0, |
22
|
|
|
self::OPTION_ERROR_MARGIN => 0, |
23
|
|
|
]; |
24
|
|
|
|
25
|
|
|
protected function normalizeRatio($ratio) |
26
|
|
|
{ |
27
|
|
|
if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) { |
28
|
|
|
return floatval($ratio); |
29
|
|
|
} |
30
|
|
|
if (strpos($ratio, ':') !== false) { |
31
|
|
|
list($width, $height) = explode(':', $ratio); |
32
|
|
|
|
33
|
|
|
return $width / $height; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return 0; |
37
|
|
|
} |
38
|
|
|
|
39
|
7 |
|
public function validate($value, string $valueIdentifier = null) |
40
|
|
|
{ |
41
|
7 |
|
$this->value = $value; |
42
|
7 |
|
$ratio = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]); |
43
|
7 |
|
if (! file_exists($value)) { |
44
|
1 |
|
$this->success = false; |
45
|
6 |
|
} elseif ($ratio == 0) { |
46
|
2 |
|
$this->success = true; |
47
|
|
|
} else { |
48
|
4 |
|
$imageInfo = getimagesize($value); |
49
|
|
|
|
50
|
4 |
|
if (is_array($imageInfo)) { |
51
|
3 |
|
$actualRatio = $imageInfo[0] / $imageInfo[1]; |
52
|
3 |
|
$this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN]; |
53
|
|
|
} else { |
54
|
|
|
// no image size computed => no valid image |
55
|
1 |
|
return $this->success = false; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
6 |
|
return $this->success; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|