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

ImageRatio::validate()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0106

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 14
cts 15
cp 0.9333
rs 8.9137
c 0
b 0
f 0
cc 6
nc 5
nop 2
crap 6.0106
1
<?php
2
declare(strict_types=1);
3
namespace Sirius\Validation\Rule\Upload;
4
5
use Sirius\Validation\Rule\AbstractRule;
6
use Sirius\Validation\Util\RuleHelper;
7
8
class ImageRatio extends AbstractRule
9
{
10
    // the image width/height ration;
11
    // can be a number or a string like 4:3, 16:9
12
    const OPTION_RATIO = 'ratio';
13
    // how much can the image ratio diverge from the allowed ratio
14
    const OPTION_ERROR_MARGIN = 'error_margin';
15
16
    const MESSAGE = 'The image does must have a ratio (width/height) of {ratio})';
17
18
    const LABELED_MESSAGE = '{label} does must have a ratio (width/height) of {ratio})';
19
20
    protected $options = [
21
        self::OPTION_RATIO        => 0,
22
        self::OPTION_ERROR_MARGIN => 0,
23
    ];
24
25 8
    public function validate($value, string $valueIdentifier = null)
26
    {
27 8
        $this->value = $value;
28 8
        $ratio       = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]);
29 8
        if (! is_array($value) || ! isset($value['tmp_name'])) {
30
            $this->success = false;
31 8
        } elseif (! file_exists($value['tmp_name'])) {
32 2
            $this->success = $value['error'] === UPLOAD_ERR_NO_FILE;
33 6
        } elseif ($ratio == 0) {
34 2
            $this->success = true;
35
        } else {
36 4
            $imageInfo     = getimagesize($value['tmp_name']);
37
38 4
            if (is_array($imageInfo)) {
39 3
                $actualRatio   = $imageInfo[0] / $imageInfo[1];
40 3
                $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN];
41
            } else {
42
                // no image size computed => no valid image
43 1
                return $this->success = false;
44
            }
45
        }
46
47 7
        return $this->success;
48
    }
49
}
50