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

FileFieldMaxRule::validateMax()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
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
                    return true;
18
                }
19
            }
20
        }
21
22
        $validator->setCustomMessages([
23
            'filefield_max' => 'De :attribute is te groot en dient kleiner te zijn dan ' . implode(',',$params) .'Kb.',
24
        ]);
25
26
        if(!isset($validator->customAttributes[$attribute])) {
27
            $validator->addCustomAttributes([
28
                $attribute => 'afbeelding',
29
            ]);
30
        }
31
32
33
        return false;
34
    }
35
36
    public function validateMax($attribute, $value, $parameters)
37
    {
38
        if($this->refersToExistingAsset($value)) {
39
            return $this->validateAssetMax($this->existingAsset($value), $parameters);
40
        }
41
42
        return parent::validateMax($attribute, $value, $parameters);
43
    }
44
45
    /**
46
     * A method required by the validateMax method
47
     *
48
     * @param $attribute
49
     * @param $value
50
     * @return float|int
51
     */
52
    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

52
    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...
53
    {
54
        if(!$value instanceof File) {
55
            throw new \InvalidArgumentException('Value is expected to be of type ' . File::class);
56
        }
57
58
        return $value->getSize() / 1024;
59
    }
60
}
61