Test Failed
Push — fix/media-validation ( 6403fc...e4808d )
by Ben
07:03
created

FileFieldMinRule::addCustomValidationMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 3
1
<?php declare(strict_types=1);
2
3
namespace Thinktomorrow\Chief\Fields\ValidationRules;
4
5
use Thinktomorrow\Chief\Media\Application\MediaRequest;
6
7
class FileFieldMinRule 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->validateMin($attribute, $file, $params)) {
16
                    $this->addCustomValidationMessage($attribute, $params, $validator);
17
18
                    return false;
19
                }
20
            }
21
        }
22
23
        return true;
24
    }
25
26
    public function validateMin($attribute, $value, $parameters)
27
    {
28
        if($this->refersToExistingAsset($value)) {
29
            return $this->validateAssetMin($this->existingAsset($value), $parameters);
30
        }
31
32
        return parent::validateMin($attribute, $value, $parameters);
33
    }
34
35
    /**
36
     * @param $attribute
37
     * @param $params
38
     * @param $validator
39
     */
40
    private function addCustomValidationMessage($attribute, $params, $validator): void
41
    {
42
        $validator->setCustomMessages([
43
            'filefield_min' => 'De :attribute is te klein en dient groter te zijn dan ' . implode(',', $params) . 'Kb.',
44
        ]);
45
46
        if (!isset($validator->customAttributes[$attribute])) {
47
            $validator->addCustomAttributes([
48
                $attribute => 'afbeelding',
49
            ]);
50
        }
51
    }
52
}
53