1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\ValidationRules; |
4
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Media\Application\MediaRequest; |
6
|
|
|
|
7
|
|
|
class ImageFieldMaxRule 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->validateMax($attribute, $file, $params)) { |
16
|
|
|
return true; |
17
|
|
|
} |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
$validator->setCustomMessages([ |
22
|
|
|
'imagefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',',$params) .'Kb.', |
23
|
|
|
]); |
24
|
|
|
|
25
|
|
|
if(!isset($validator->customAttributes[$attribute])) { |
26
|
|
|
$validator->addCustomAttributes([ |
27
|
|
|
$attribute => 'afbeelding', |
28
|
|
|
]); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
return false; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function validateMax($attribute, $value, $parameters) |
36
|
|
|
{ |
37
|
|
|
$this->requireParameterCount(1, $parameters, 'max'); |
38
|
|
|
|
39
|
|
|
return $this->getSize($attribute, $value) <= $parameters[0]; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* A method required by the validateMax method |
44
|
|
|
* |
45
|
|
|
* @param $attribute |
46
|
|
|
* @param $value |
47
|
|
|
* @return float|int |
48
|
|
|
*/ |
49
|
|
|
protected function getSize($attribute, $value) |
|
|
|
|
50
|
|
|
{ |
51
|
|
|
$file = json_decode($value)->output; |
52
|
|
|
|
53
|
|
|
return $this->getBase64ImageSize($file->image) / 1024; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function getBase64ImageSize($value) |
57
|
|
|
{ |
58
|
|
|
return strlen(base64_decode($value)); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.