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

FileFieldMaxRule::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 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
                    $this->addCustomValidationMessage($attribute, $params, $validator);
18
                    return false;
19
                }
20
            }
21
        }
22
23
        return true;
24
    }
25
26
    public function validateMax($attribute, $value, $parameters)
27
    {
28
        if($this->refersToExistingAsset($value)) {
29
            return $this->validateAssetMax($this->existingAsset($value), $parameters);
30
        }
31
32
        return parent::validateMax($attribute, $value, $parameters);
33
    }
34
35
    /**
36
     * A method required by the validateMax method
37
     *
38
     * @param $attribute
39
     * @param $value
40
     * @return float|int
41
     */
42
    protected function getSize($attribute, $value)
43
    {
44
        if(!$value instanceof File) {
45
            throw new \InvalidArgumentException('Value is expected to be of type ' . File::class);
46
        }
47
48
        return $value->getSize() / 1024;
49
    }
50
51
    /**
52
     * @param $attribute
53
     * @param $params
54
     * @param $validator
55
     */
56
    private function addCustomValidationMessage($attribute, $params, $validator): void
57
    {
58
        $validator->setCustomMessages([
59
            'filefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',', $params) . 'Kb.',
60
        ]);
61
62
        if (!isset($validator->customAttributes[$attribute])) {
63
            $validator->addCustomAttributes([
64
                $attribute => 'afbeelding',
65
            ]);
66
        }
67
    }
68
}
69