Completed
Push — master ( d45ca1...554243 )
by Adrian
01:42
created

Image::validate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6.0359

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.2222
c 0
b 0
f 0
cc 6
nc 6
nop 2
crap 6.0359
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Validation\Rule\Upload;
5
6
use Sirius\Validation\Rule\AbstractRule;
7
8
class Image extends AbstractRule
9
{
10
    const OPTION_ALLOWED_IMAGES = 'allowed';
11
12
    const MESSAGE = 'The file is not a valid image (only {image_types} are allowed)';
13
14
    const LABELED_MESSAGE = '{label} is not a valid image (only {image_types} are allowed)';
15
16
    protected $options = [
17
        self::OPTION_ALLOWED_IMAGES => ['jpg', 'png', 'gif']
18
    ];
19
20
    protected $imageTypesMap = [
21
        IMAGETYPE_GIF      => 'gif',
22
        IMAGETYPE_JPEG     => 'jpg',
23
        IMAGETYPE_JPEG2000 => 'jpg',
24
        IMAGETYPE_PNG      => 'png',
25
        IMAGETYPE_PSD      => 'psd',
26
        IMAGETYPE_BMP      => 'bmp',
27
        IMAGETYPE_ICO      => 'ico',
28
    ];
29
30 4
    public function setOption($name, $value)
31
    {
32 4
        if ($name == self::OPTION_ALLOWED_IMAGES) {
33 4
            if (is_string($value)) {
34 1
                $value = explode(',', $value);
35
            }
36 4
            $value = array_map('trim', $value);
37 4
            $value = array_map('strtolower', $value);
38
        }
39
40 4
        return parent::setOption($name, $value);
41
    }
42
43 5
    public function validate($value, string $valueIdentifier = null)
44
    {
45 5
        $this->value = $value;
46 5
        if (! is_array($value) || ! isset($value['tmp_name'])) {
47
            $this->success = false;
48 5
        } elseif (! file_exists($value['tmp_name'])) {
49 2
            $this->success = $value['error'] === UPLOAD_ERR_NO_FILE;
50
        } else {
51 3
            $imageInfo     = getimagesize($value['tmp_name']);
52 3
            $extension     = isset($this->imageTypesMap[$imageInfo[2]]) ? $this->imageTypesMap[$imageInfo[2]] : false;
53 3
            $this->success = ($extension && in_array($extension, $this->options[self::OPTION_ALLOWED_IMAGES]));
54
        }
55
56 5
        return $this->success;
57
    }
58
59 1
    public function getPotentialMessage()
60
    {
61 1
        $message    = parent::getPotentialMessage();
62 1
        $imageTypes = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_IMAGES]);
63 1
        $message->setVariables([
64 1
            'image_types' => implode(', ', $imageTypes)
65
        ]);
66
67 1
        return $message;
68
    }
69
}
70