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

ImageFieldMinRule::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 ImageFieldMinRule 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
17
                    $this->addCustomValidationMessage($attribute, $params, $validator);
18
19
                    return false;
20
                }
21
            }
22
        }
23
24
        return true;
25
    }
26
27
    public function validateMin($attribute, $value, $parameters)
28
    {
29
        if($this->refersToExistingAsset($value)) {
30
            return $this->validateAssetMin($this->existingAsset($value), $parameters);
31
        }
32
33
        $this->requireParameterCount(1, $parameters, 'min');
34
35
        return $this->getSize($attribute, $value) >= $parameters[0];
36
    }
37
38
    /**
39
     * A method required by the validateMax method
40
     *
41
     * @param $attribute
42
     * @param $value
43
     * @return float|int
44
     */
45
    protected function getSize($attribute, $value)
46
    {
47
        $inputData = json_decode($value)->input;
48
49
        // size in Kilobytes (slim component already provides a size that, due to the way slim stored this,
50
        //  we need reduce to kilobytes by dividing 1000 instead of the expected 1024.
51
        return $inputData->size / 1000;
52
    }
53
54
    /**
55
     * @param $attribute
56
     * @param $params
57
     * @param $validator
58
     */
59
    private function addCustomValidationMessage($attribute, $params, $validator): void
60
    {
61
        $validator->setCustomMessages([
62
            'imagefield_min' => 'De :attribute is te klein en dient groter te zijn dan ' . implode(',', $params) . 'Kb.',
63
        ]);
64
65
        if (!isset($validator->customAttributes[$attribute])) {
66
            $validator->addCustomAttributes([
67
                $attribute => 'afbeelding',
68
            ]);
69
        }
70
    }
71
}
72