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

Extension::validate()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6.0087

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
ccs 15
cts 16
cp 0.9375
rs 8.7624
cc 6
eloc 15
nc 5
nop 2
crap 6.0087
1
<?php
2
3
namespace Sirius\Validation\Rule\Upload;
4
5
use Sirius\Validation\Rule\AbstractRule;
6
7
class Extension extends AbstractRule
8
{
9
    const OPTION_ALLOWED_EXTENSIONS = 'allowed';
10
11
    const MESSAGE = 'The file does not have an acceptable extension ({file_extensions})';
12
13
    const LABELED_MESSAGE = '{label} does not have an acceptable extension ({file_extensions})';
14
15
    protected $options = array(
16
        self::OPTION_ALLOWED_EXTENSIONS => array()
17
    );
18
19 4
    public function setOption($name, $value)
20
    {
21 4
        if ($name == self::OPTION_ALLOWED_EXTENSIONS) {
22 4
            if (is_string($value)) {
23 1
                $value = explode(',', $value);
24 1
            }
25 4
            $value = array_map('trim', $value);
26 4
            $value = array_map('strtolower', $value);
27 4
        }
28
29 4
        return parent::setOption($name, $value);
30
    }
31
32 4
    public function validate($value, $valueIdentifier = null)
33
    {
34 4
        $this->value = $value;
35 4
        if (! is_array($value) || ! isset($value['tmp_name'])) {
36
            $this->success = false;
37 4
        } else if(! file_exists($value['tmp_name'])) {
38 2
            if($value['error'] === UPLOAD_ERR_NO_FILE ){
39 1
                $this->success = true;
40 1
            }else{
41 1
                $this->success = false;
42
            }
43 2
        } else {
44 2
            $extension     = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10));
45 2
            $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array(
46 2
                $extension,
47 2
                $this->options[self::OPTION_ALLOWED_EXTENSIONS]
48 2
            );
49
        }
50
51 4
        return $this->success;
52
    }
53
54 1
    public function getPotentialMessage()
55
    {
56 1
        $message        = parent::getPotentialMessage();
57 1
        $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]);
58 1
        $message->setVariables(
59
            array(
60 1
                'file_extensions' => implode(', ', $fileExtensions)
61 1
            )
62 1
        );
63
64 1
        return $message;
65
    }
66
}
67