Completed
Push — master ( fc24c1...fa6fad )
by Adrian
14s
created

ImageRatio   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 54
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeRatio() 0 13 4
B validate() 0 22 4
1
<?php
2
namespace Sirius\Validation\Rule\File;
3
4
use Sirius\Validation\Rule\AbstractRule;
5
6
class ImageRatio extends AbstractRule
7
{
8
    // the image width/height ration;
9
    // can be a number or a string like 4:3, 16:9
10
    const OPTION_RATIO = 'ratio';
11
    // how much can the image ratio diverge from the allowed ratio
12
    const OPTION_ERROR_MARGIN = 'error_margin';
13
14
    const MESSAGE = 'The image does must have a ratio (width/height) of {ratio})';
15
16
    const LABELED_MESSAGE = '{label} does must have a ratio (width/height) of {ratio})';
17
18
    protected $options = array(
19
        self::OPTION_RATIO        => 0,
20
        self::OPTION_ERROR_MARGIN => 0,
21
    );
22
23 6
    protected function normalizeRatio($ratio)
24
    {
25 6
        if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) {
26 4
            return floatval($ratio);
27
        }
28 2
        if (strpos($ratio, ':') !== false) {
29 1
            list($width, $height) = explode(':', $ratio);
30
31 1
            return $width / $height;
32
        }
33
34 1
        return 0;
35
    }
36
37 6
    public function validate($value, $valueIdentifier = null)
38
    {
39 6
        $this->value = $value;
40 6
        $ratio       = $this->normalizeRatio($this->options[self::OPTION_RATIO]);
41 6
        if (! file_exists($value)) {
42 1
            $this->success = false;
43 6
        } elseif ($ratio == 0) {
44 2
            $this->success = true;
45 2
        } else {
46 3
            $imageInfo     = getimagesize($value);
47 3
48 3
            if (is_array($imageInfo)) {
49
                $actualRatio   = $imageInfo[0] / $imageInfo[1];
50
                $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN];
51 6
            } else {
52
                // no image size computed => no valid image
53
                return $this->success = false;
54
            }
55
        }
56
57
        return $this->success;
58
    }
59
}
60