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

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 FileFieldDimensionsRule 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
                    $this->addCustomValidationMessage($attribute, $params, $validator);
17
                    return false;
18
                }
19
            }
20
        }
21
22
        return true;
23
    }
24
25
    public function validateDimensions($attribute, $value, $parameters)
26
    {
27
        if($this->refersToExistingAsset($value)) {
28
            return $this->validateAssetDimensions($this->existingAsset($value), $parameters);
29
        }
30
31
        return parent::validateDimensions($attribute, $value, $parameters);
32
    }
33
34
    /**
35
     * @param $attribute
36
     * @param $params
37
     * @param $validator
38
     */
39
    private function addCustomValidationMessage($attribute, $params, $validator): void
40
    {
41
        $validator->setCustomMessages([
42
            'filefield_dimensions' => 'De :attribute heeft niet de juiste afmetingen: ' . implode(', ', $params),
43
        ]);
44
45
        if (!isset($validator->customAttributes[$attribute])) {
46
            $validator->addCustomAttributes([
47
                $attribute => 'afbeelding',
48
            ]);
49
        }
50
    }
51
}
52