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

FileFieldMinRule   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 16
c 1
b 0
f 0
dl 0
loc 42
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addCustomValidationMessage() 0 9 2
A validateMin() 0 7 2
A validate() 0 15 5
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