Completed
Push — master ( d45ca1...554243 )
by Adrian
01:42
created

Extension::getPotentialMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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