Completed
Push — unit-tests-validation ( a1f155...85f064 )
by Romain
02:26
created

ContainsValuesValidator::valuesAreInArray()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 12
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 => [[], 'The values that are accepted, can be a string of valued delimited by a pipe.', 'array', true]
30
    ];
31
32
    /**
33
     * @inheritdoc
34
     */
35
    protected $supportedMessages = [
36
        self::MESSAGE_DEFAULT => [
37
            'key'       => 'validator.form.contains_values.error',
38
            'extension' => null
39
        ],
40
        self::MESSAGE_EMPTY   => [
41
            'key'       => 'validator.form.required.error',
42
            'extension' => null
43
        ]
44
    ];
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function isValid($values)
50
    {
51
        if (false === is_array($values)) {
52
            $values = [$values];
53
        }
54
55
        if (empty($values)) {
56
            $this->addError(self::MESSAGE_EMPTY, 1487943450);
57
        } else {
58
            $this->valuesAreInArray($values);
59
        }
60
    }
61
62
    /**
63
     * @param array $values
64
     */
65
    protected function valuesAreInArray(array $values)
66
    {
67
        $flag = true;
68
        $acceptedValues = $this->options[self::OPTION_VALUES];
69
70
        if (false === is_array($acceptedValues)) {
71
            $acceptedValues = GeneralUtility::trimExplode('|', $acceptedValues);
72
        }
73
74
        foreach ($values as $value) {
75
            $flag = $flag && in_array($value, $acceptedValues);
76
        }
77
78
        if (false === $flag) {
79
            $this->addError(
80
                self::MESSAGE_DEFAULT,
81
                1445952458,
82
                [implode(', ', $acceptedValues)]
83
            );
84
        }
85
    }
86
}
87