1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\ValidationRules; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\File\File; |
6
|
|
|
use Thinktomorrow\Chief\Media\Application\MediaRequest; |
7
|
|
|
|
8
|
|
|
class FileFieldMaxRule extends AbstractMediaFieldRule |
9
|
|
|
{ |
10
|
|
|
public function validate($attribute, $value, $params, $validator): bool |
11
|
|
|
{ |
12
|
|
|
$value = $this->normalizePayload($value); |
13
|
|
|
|
14
|
|
|
foreach([MediaRequest::NEW, MediaRequest::REPLACE] as $type) { |
15
|
|
|
foreach($value[$type] as $file) { |
16
|
|
|
if($file && false !== $this->validateMax($attribute, $file, $params)) { |
17
|
|
|
return true; |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
$validator->setCustomMessages([ |
23
|
|
|
'filefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',',$params) .'Kb.', |
24
|
|
|
]); |
25
|
|
|
|
26
|
|
|
if(!isset($validator->customAttributes[$attribute])) { |
27
|
|
|
$validator->addCustomAttributes([ |
28
|
|
|
$attribute => 'afbeelding', |
29
|
|
|
]); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
return false; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function validateMax($attribute, $value, $parameters) |
37
|
|
|
{ |
38
|
|
|
if($this->refersToExistingAsset($value)) { |
39
|
|
|
return $this->validateAssetMax($this->existingAsset($value), $parameters); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return parent::validateMax($attribute, $value, $parameters); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* A method required by the validateMax method |
47
|
|
|
* |
48
|
|
|
* @param $attribute |
49
|
|
|
* @param $value |
50
|
|
|
* @return float|int |
51
|
|
|
*/ |
52
|
|
|
protected function getSize($attribute, $value) |
|
|
|
|
53
|
|
|
{ |
54
|
|
|
if(!$value instanceof File) { |
55
|
|
|
throw new \InvalidArgumentException('Value is expected to be of type ' . File::class); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $value->getSize() / 1024; |
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.