Completed
Pull Request — master (#61)
by
unknown
01:35
created

Extension::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 12
cts 13
cp 0.9231
c 0
b 0
f 0
rs 9.3888
cc 5
nc 4
nop 2
crap 5.0113
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
        } elseif (! file_exists($value['tmp_name'])) {
38 2
            $this->success = $value['error'] === UPLOAD_ERR_NO_FILE;
39 2
        } else {
40 2
            $extension     = strtolower(substr($value['name'], strrpos($value['name'], '.') + 1, 10));
41 2
            $this->success = is_array($this->options[self::OPTION_ALLOWED_EXTENSIONS]) && in_array(
42 2
                $extension,
43 2
                $this->options[self::OPTION_ALLOWED_EXTENSIONS]
44 2
            );
45
        }
46
47 4
        return $this->success;
48
    }
49
50 1
    public function getPotentialMessage()
51
    {
52 1
        $message        = parent::getPotentialMessage();
53 1
        $fileExtensions = array_map('strtoupper', $this->options[self::OPTION_ALLOWED_EXTENSIONS]);
54 1
        $message->setVariables(
55
            array(
56 1
                'file_extensions' => implode(', ', $fileExtensions)
57 1
            )
58 1
        );
59
60 1
        return $message;
61
    }
62
}
63