Passed
Push — master ( 800bc9...20faea )
by Lee
06:38
created

ImageUpload::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 0
dl 0
loc 22
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace Lavibi\Popoya;
4
5
class ImageUpload extends UploadFile
6
{
7
    const MAX_WIDTH = 'max_width';
8
    const MAX_HEIGHT = 'max_height';
9
10
    public function hasMaxWidth($width)
11
    {
12
        $this->options['size']['width'] = (int) $width;
13
14
        return $this;
15
    }
16
17
    public function hasMaxHeight($height)
18
    {
19
        $this->options['size']['height'] = (int) $height;
20
21
        return $this;
22
    }
23
24
    /**
25
     * @param array $value
26
     *
27
     * @return bool
28
     */
29
    public function isValid($value)
30
    {
31
        if (!parent::isValid($value)) {
32
            return false;
33
        }
34
35
        $image = $this->isImageFile($value['tmp_name']);
36
37
        if (!$image) {
38
            return false;
39
        }
40
41
        if (!$this->isValidImageMaxSize($image['width'], $image['height'])) {
42
            return false;
43
        }
44
45
        $this->standardValue['image'] = $image;
46
47
        return true;
48
    }
49
50
    protected function isImageFile($filePath)
51
    {
52
        $size = getimagesize($filePath);
53
54
        if ($size === false) {
55
            $this->setError(self::NOT_VALID_TYPE);
56
            return false;
57
        }
58
59
        return [
60
            'width' => $size[0],
61
            'height' => $size[1],
62
        ];
63
    }
64
65
    protected function isValidImageMaxSize($width, $height)
66
    {
67
        if ($this->options['size']['width'] !== 0 && $width > $this->options['size']['width']) {
68
            $this->setError(self::MAX_WIDTH);
69
            return false;
70
        }
71
72
        if ($this->options['size']['height'] !== 0 && $height > $this->options['size']['height']) {
73
            $this->setError(self::MAX_HEIGHT);
74
            return false;
75
        }
76
77
        return true;
78
    }
79
80
    protected function init()
81
    {
82
        parent::init();
83
84
        $this->defaultOptions['type'] = [
85
            'image/gif',
86
            'image/jpg',
87
            'image/jpeg',
88
            'image/jpe',
89
            'image/pjpeg',
90
            'image/png',
91
            'img/x-png'
92
        ];
93
94
        $this->defaultOptions['size'] = [
95
            'width' => 0,
96
            'height' => 0,
97
        ];
98
99
        $this->messages[self::NOT_VALID_TYPE] = 'Uploaded file was not image type.';
100
        $this->messages[self::MAX_WIDTH] = 'Image width is too large.';
101
        $this->messages[self::MAX_HEIGHT] = 'Image height is too large.';
102
    }
103
}
104