Passed
Push — master ( e8719f...9c9dec )
by
unknown
39:13 queued 22:29
created

AbstractValidator::isEmpty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Extbase\Validation\Validator;
17
18
use TYPO3\CMS\Extbase\Error\Result;
19
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
20
use TYPO3\CMS\Extbase\Validation\Error;
21
use TYPO3\CMS\Extbase\Validation\Exception\InvalidValidationOptionsException;
22
23
/**
24
 * Abstract validator
25
 */
26
abstract class AbstractValidator implements ValidatorInterface
27
{
28
    /**
29
     * Specifies whether this validator accepts empty values.
30
     *
31
     * If this is TRUE, the validators isValid() method is not called in case of an empty value
32
     * Note: A value is considered empty if it is NULL or an empty string!
33
     * By default all validators except for NotEmpty and the Composite Validators accept empty values
34
     *
35
     * @var bool
36
     */
37
    protected $acceptsEmptyValues = true;
38
39
    /**
40
     * This contains the supported options, their default values, types and descriptions.
41
     *
42
     * @var array
43
     */
44
    protected $supportedOptions = [];
45
46
    /**
47
     * @var array
48
     */
49
    protected $options = [];
50
51
    /**
52
     * @var \TYPO3\CMS\Extbase\Error\Result
53
     */
54
    protected $result;
55
56
    /**
57
     * Constructs the validator and sets validation options
58
     *
59
     * @param array $options Options for the validator
60
     * @throws InvalidValidationOptionsException
61
     */
62
    public function __construct(array $options = [])
63
    {
64
        // check for options given but not supported
65
        if (($unsupportedOptions = array_diff_key($options, $this->supportedOptions)) !== []) {
66
            throw new InvalidValidationOptionsException('Unsupported validation option(s) found: ' . implode(', ', array_keys($unsupportedOptions)), 1379981890);
67
        }
68
69
        // check for required options being set
70
        array_walk(
71
            $this->supportedOptions,
72
            function ($supportedOptionData, $supportedOptionName, $options) {
73
                if (isset($supportedOptionData[3]) && $supportedOptionData[3] === true && !array_key_exists($supportedOptionName, $options)) {
74
                    throw new InvalidValidationOptionsException('Required validation option not set: ' . $supportedOptionName, 1379981891);
75
                }
76
            },
77
            $options
78
        );
79
80
        // merge with default values
81
        $this->options = array_merge(
82
            array_map(
83
                function ($value) {
84
                    return $value[0];
85
                },
86
                $this->supportedOptions
87
            ),
88
            $options
89
        );
90
    }
91
92
    /**
93
     * Checks if the given value is valid according to the validator, and returns
94
     * the error messages object which occurred.
95
     *
96
     * @param mixed $value The value that should be validated
97
     * @return \TYPO3\CMS\Extbase\Error\Result
98
     */
99
    public function validate($value)
100
    {
101
        $this->result = new Result();
102
        if ($this->acceptsEmptyValues === false || $this->isEmpty($value) === false) {
103
            $this->isValid($value);
104
        }
105
        return $this->result;
106
    }
107
108
    /**
109
     * Check if $value is valid. If it is not valid, needs to add an error
110
     * to result.
111
     *
112
     * @param mixed $value
113
     */
114
    abstract protected function isValid($value);
115
116
    /**
117
     * Creates a new validation error object and adds it to $this->result
118
     *
119
     * @param string $message The error message
120
     * @param int $code The error code (a unix timestamp)
121
     * @param array $arguments Arguments to be replaced in message
122
     * @param string $title title of the error
123
     */
124
    protected function addError($message, $code, array $arguments = [], $title = '')
125
    {
126
        $this->result->addError(new Error((string)$message, (int)$code, $arguments, (string)$title));
127
    }
128
129
    /**
130
     * Creates a new validation error object for a property and adds it to the proper sub result of $this->result
131
     *
132
     * @param string|array $message The property path (string or array)
133
     * @param string $message The error message
134
     * @param int $code The error code (a unix timestamp)
135
     * @param array $arguments Arguments to be replaced in message
136
     * @param string $title title of the error
137
     */
138
    protected function addErrorForProperty($propertyPath, $message, $code, array $arguments = [], $title = '')
139
    {
140
        $propertyPath = is_array($propertyPath) ? implode('.', $propertyPath) : (string)$propertyPath;
141
        $error = new Error((string)$message, (int)$code, $arguments, (string)$title);
142
        $this->result->forProperty($propertyPath)->addError($error);
143
    }
144
145
    /**
146
     * Returns the options of this validator
147
     *
148
     * @return array
149
     */
150
    public function getOptions()
151
    {
152
        return $this->options;
153
    }
154
155
    /**
156
     * @param mixed $value
157
     * @return bool TRUE if the given $value is NULL or an empty string ('')
158
     */
159
    final protected function isEmpty($value)
160
    {
161
        return $value === null || $value === '';
162
    }
163
164
    /**
165
     * Wrap static call to LocalizationUtility to simplify unit testing
166
     *
167
     * @param string $translateKey
168
     * @param string $extensionName
169
     * @param array $arguments
170
     *
171
     * @return string
172
     */
173
    protected function translateErrorMessage($translateKey, $extensionName, $arguments = []): string
174
    {
175
        return LocalizationUtility::translate(
176
            $translateKey,
177
            $extensionName,
178
            $arguments
179
        ) ?? '';
180
    }
181
}
182