Test Failed
Push — fix/media-validation ( 3351fe )
by Ben
09:34
created

ImageFieldMaxRule   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getBase64ImageSize() 0 3 1
A getSize() 0 5 1
A validate() 0 24 6
A validateMax() 0 5 1
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
                    return true;
17
                }
18
            }
19
        }
20
21
        $validator->setCustomMessages([
22
            'imagefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',',$params) .'Kb.',
23
        ]);
24
25
        if(!isset($validator->customAttributes[$attribute])) {
26
            $validator->addCustomAttributes([
27
                $attribute => 'afbeelding',
28
            ]);
29
        }
30
31
32
        return false;
33
    }
34
35
    public function validateMax($attribute, $value, $parameters)
36
    {
37
        $this->requireParameterCount(1, $parameters, 'max');
38
39
        return $this->getSize($attribute, $value) <= $parameters[0];
40
    }
41
42
    /**
43
     * A method required by the validateMax method
44
     *
45
     * @param $attribute
46
     * @param $value
47
     * @return float|int
48
     */
49
    protected function getSize($attribute, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

49
    protected function getSize(/** @scrutinizer ignore-unused */ $attribute, $value)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51
        $file = json_decode($value)->output;
52
53
        return $this->getBase64ImageSize($file->image) / 1024;
54
    }
55
56
    private function getBase64ImageSize($value)
57
    {
58
        return strlen(base64_decode($value));
59
    }
60
}
61