Completed
Pull Request — master (#42)
by
unknown
05:15
created

ImageRatio::validate()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6.0073

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
ccs 16
cts 17
cp 0.9412
rs 8.6737
cc 6
eloc 17
nc 5
nop 2
crap 6.0073
1
<?php
2
namespace Sirius\Validation\Rule\Upload;
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 7
    protected function normalizeRatio($ratio)
24
    {
25 7
        if (is_numeric($ratio) || $ratio == filter_var($ratio, FILTER_SANITIZE_NUMBER_FLOAT)) {
26 5
            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 7
    public function validate($value, $valueIdentifier = null)
38
    {
39 7
        $this->value = $value;
40 7
        $ratio       = $this->normalizeRatio($this->options[self::OPTION_RATIO]);
41 7
        if (! is_array($value) || ! isset($value['tmp_name'])) {
42
            $this->success = false;
43 7
        } else if(! file_exists($value['tmp_name'])) {
44 2
            if($value['error'] === UPLOAD_ERR_NO_FILE ){
45 1
                $this->success = true;
46 1
            }else{
47 1
                $this->success = false;
48
            }
49 7
        } else if ($ratio == 0) {
50 2
            $this->success = true;
51 2
        } else {
52 3
            $imageInfo     = getimagesize($value['tmp_name']);
53 3
            $actualRatio   = $imageInfo[0] / $imageInfo[1];
54 3
            $this->success = abs($actualRatio - $ratio) <= $this->options[self::OPTION_ERROR_MARGIN];
55
        }
56
57 7
        return $this->success;
58
    }
59
}
60