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

Extension   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 96.67%

Importance

Changes 0
Metric Value
dl 0
loc 56
ccs 29
cts 30
cp 0.9667
c 0
b 0
f 0
wmc 9
lcom 1
cbo 2
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setOption() 0 12 3
A validate() 0 17 5
A getPotentialMessage() 0 12 1
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