ImageValidator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace VSV\GVQ_API\Image\Validation;
4
5
use Symfony\Component\HttpFoundation\File\UploadedFile;
6
7
class ImageValidator implements UploadFileValidator
8
{
9
    /** @var int */
10
    private $maxFileSize;
11
12
    /** @var string[] */
13
    private $supportedMimeTypes;
14
15
    /**
16
     * @param int $maxFileSize in bytes
17
     * @param string[] $supportedMimeTypes
18
     */
19
    public function __construct(int $maxFileSize, array $supportedMimeTypes)
20
    {
21
        $this->maxFileSize = $maxFileSize;
22
        $this->supportedMimeTypes = $supportedMimeTypes;
23
    }
24
25
    /**
26
     * @inheritdoc
27
     */
28
    public function validate(UploadedFile $uploadedFile): void
29
    {
30
        if (!$uploadedFile->isValid()) {
31
            throw new \InvalidArgumentException(
32
                'Image was not uploaded successful.'
33
            );
34
        }
35
36
        $bytes = $uploadedFile->getClientSize();
37
        if ($bytes > $this->maxFileSize) {
38
            $mb = $this->maxFileSize / (1024 * 1024);
39
            throw new \InvalidArgumentException('File is bigger then '.$mb.' MB.');
40
        }
41
42
        if (!in_array($uploadedFile->getMimeType(), $this->supportedMimeTypes)) {
43
            $types = implode(', ', $this->supportedMimeTypes);
44
            throw new \InvalidArgumentException('Only image types '.$types.' are supported.');
45
        }
46
    }
47
}
48