Completed
Pull Request — master (#61)
by
unknown
01:35
created

Image::validate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.027

Importance

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