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

ImageFieldMaxRule::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 ImageFieldMaxRule 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->validateMax($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 validateMax($attribute, $value, $parameters)
28
    {
29
        if($this->refersToExistingAsset($value)) {
30
            return $this->validateAssetMax($this->existingAsset($value), $parameters);
31
        }
32
33
        $this->requireParameterCount(1, $parameters, 'max');
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
        $file = json_decode($value)->output;
48
49
        return $this->getBase64ImageSize($file->image) / 1024;
50
    }
51
52
    private function getBase64ImageSize($value)
53
    {
54
        return strlen(base64_decode($value));
55
    }
56
57
    /**
58
     * @param $attribute
59
     * @param $params
60
     * @param $validator
61
     */
62
    private function addCustomValidationMessage($attribute, $params, $validator): void
63
    {
64
        $validator->setCustomMessages([
65
            'imagefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',', $params) . 'Kb.',
66
        ]);
67
68
        if (!isset($validator->customAttributes[$attribute])) {
69
            $validator->addCustomAttributes([
70
                $attribute => 'afbeelding',
71
            ]);
72
        }
73
    }
74
}
75