ContainsValuesValidator::valuesAreInArray()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.2728
c 0
b 0
f 0
cc 5
nc 12
nop 1
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 FormZ project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Validation\Validator;
15
16
use TYPO3\CMS\Core\Utility\GeneralUtility;
17
18
class ContainsValuesValidator extends AbstractValidator
19
{
20
    const OPTION_VALUES = 'values';
21
22
    const MESSAGE_DEFAULT = 'default';
23
    const MESSAGE_EMPTY = 'empty';
24
25
    /**
26
     * @inheritdoc
27
     */
28
    protected $supportedOptions = [
29
        self::OPTION_VALUES => [
30
            [],
31
            'The values that are accepted, can be a string of valued delimited by a pipe.',
32
            'array',
33
            true
34
        ]
35
    ];
36
37
    /**
38
     * @inheritdoc
39
     */
40
    protected $supportedMessages = [
41
        self::MESSAGE_DEFAULT => [
42
            'key'       => 'validator.form.contains_values.error',
43
            'extension' => null
44
        ],
45
        self::MESSAGE_EMPTY   => [
46
            'key'       => 'validator.form.required.error',
47
            'extension' => null
48
        ]
49
    ];
50
51
    /**
52
     * @inheritdoc
53
     */
54
    public function isValid($values)
55
    {
56
        if (false === is_array($values)) {
57
            $values = [$values];
58
        }
59
60
        if (empty($values)) {
61
            $this->addError(self::MESSAGE_EMPTY, 1487943450);
62
        } else {
63
            $this->valuesAreInArray($values);
64
        }
65
    }
66
67
    /**
68
     * @param array $values
69
     */
70
    protected function valuesAreInArray(array $values)
71
    {
72
        $flag = true;
73
        $acceptedValues = $this->options[self::OPTION_VALUES];
74
75
        if (false === is_array($acceptedValues)) {
76
            $acceptedValues = GeneralUtility::trimExplode('|', $acceptedValues);
77
        }
78
79
        foreach ($values as $value) {
80
            $flag = $flag && in_array($value, $acceptedValues);
81
        }
82
83
        if (false === $flag) {
84
            $this->addError(
85
                self::MESSAGE_DEFAULT,
86
                1445952458,
87
                [implode(', ', $acceptedValues)]
88
            );
89
        }
90
    }
91
}
92