Completed
Push — master ( 458234...a0327e )
by Adrian
01:39
created

ImageRatio   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 42
ccs 17
cts 18
cp 0.9444
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 24 6
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 7
    ];
24
25 7
    public function validate($value, string $valueIdentifier = null)
26 5
    {
27
        $this->value = $value;
28 2
        $ratio       = RuleHelper::normalizeImageRatio($this->options[self::OPTION_RATIO]);
29 1
        if (! is_array($value) || ! isset($value['tmp_name'])) {
30
            $this->success = false;
31 1
        } elseif (! file_exists($value['tmp_name'])) {
32
            $this->success = $value['error'] === UPLOAD_ERR_NO_FILE;
33
        } elseif ($ratio == 0) {
34 1
            $this->success = true;
35
        } else {
36
            $imageInfo     = getimagesize($value['tmp_name']);
37 7
38
            if (is_array($imageInfo)) {
39 7
                $actualRatio   = $imageInfo[0] / $imageInfo[1];
40 7
                $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN];
41 7
            } else {
42
                // no image size computed => no valid image
43 7
                return $this->success = false;
44 2
            }
45 1
        }
46 1
47 1
        return $this->success;
48
    }
49
}
50