1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\ValidationRules; |
4
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Media\Application\MediaRequest; |
6
|
|
|
|
7
|
|
|
class ImageFieldDimensionsRule extends AbstractMediaFieldRule |
8
|
|
|
{ |
9
|
|
|
public function validate($attribute, $value, $params, $validator): bool |
10
|
|
|
{ |
11
|
|
|
$value = $this->normalizePayload($value); |
12
|
|
|
|
13
|
|
|
foreach ([MediaRequest::NEW, MediaRequest::REPLACE] as $type) { |
14
|
|
|
foreach ($value[$type] as $file) { |
15
|
|
|
if ($file && false !== $this->validateDimensions($attribute, $file, $params)) { |
16
|
|
|
return true; |
17
|
|
|
} |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
$validator->setCustomMessages([ |
22
|
|
|
'imagefield_dimensions' => 'De :attribute heeft niet de juiste afmetingen: ' . implode(',', $this->humanReadableParams($params)), |
23
|
|
|
]); |
24
|
|
|
|
25
|
|
|
if (!isset($validator->customAttributes[$attribute])) { |
26
|
|
|
$validator->addCustomAttributes([ |
27
|
|
|
$attribute => 'afbeelding', |
28
|
|
|
]); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
return false; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Override Laravel validateDimensions to focus on the ImageField specifics |
37
|
|
|
*/ |
38
|
|
|
public function validateDimensions($attribute, $value, $parameters) |
|
|
|
|
39
|
|
|
{ |
40
|
|
|
$file = json_decode($value)->output; |
41
|
|
|
|
42
|
|
|
$width = $file->width; |
43
|
|
|
$height = $file->height; |
44
|
|
|
|
45
|
|
|
$parameters = $this->parseNamedParameters($parameters); |
46
|
|
|
|
47
|
|
|
if ($this->failsBasicDimensionChecks($parameters, $width, $height) || |
48
|
|
|
$this->failsRatioCheck($parameters, $width, $height)) { |
49
|
|
|
return false; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param $params |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
private function humanReadableParams($params): array |
60
|
|
|
{ |
61
|
|
|
$paramReplacements = [ |
62
|
|
|
'min_width' => 'minimum breedte: %s Kb', |
63
|
|
|
'max_width' => 'maximum breedte: %s Kb', |
64
|
|
|
'min_height' => 'minimum hoogte: %s Kb', |
65
|
|
|
'max_height' => 'maximum hoogte: %s Kb', |
66
|
|
|
'ratio' => 'verwachtte verhouding: %s', |
67
|
|
|
]; |
68
|
|
|
|
69
|
|
|
$humanReadableParams = []; |
70
|
|
|
|
71
|
|
|
foreach ($params as $param) { |
72
|
|
|
|
73
|
|
|
list($property, $value) = explode('=', $param); |
74
|
|
|
|
75
|
|
|
$humanReadableParams[] = isset($paramReplacements[$property]) |
76
|
|
|
? sprintf($paramReplacements[$property], $value) |
77
|
|
|
: $param; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $humanReadableParams; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
|
84
|
|
|
} |
85
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.