Completed
Push — development ( 1c9819...0be97e )
by Romain
01:56
created

AbstractValidator::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
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 Romm\Formz\Error\Error;
17
use Romm\Formz\Error\Notice;
18
use Romm\Formz\Error\Warning;
19
use Romm\Formz\Exceptions\EntryNotFoundException;
20
use Romm\Formz\Form\FormInterface;
21
use Romm\Formz\Service\MessageService;
22
use Romm\Formz\Validation\DataObject\ValidatorDataObject;
23
use TYPO3\CMS\Extbase\Error\Result;
24
25
abstract class AbstractValidator extends \TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator
26
{
27
28
    /**
29
     * Fill with paths to JavaScript files containing validation code. They will
30
     * be automatically imported when needed.
31
     *
32
     * @var array
33
     */
34
    protected static $javaScriptValidationFiles = [];
35
36
    /**
37
     * List of supported messages, which are used whenever an error occurs.
38
     * Can be overridden with TypoScript in the validator configuration.
39
     *
40
     * Example:
41
     * $supportedMessages = [
42
     *     'default'    => [
43
     *         'key'       => 'path.to.my.message',
44
     *         'extension' => 'extension_containing_message',
45
     *         'value'     => 'Some value' // Static value of the message, not recommended though.
46
     *     ]
47
     * ]
48
     *
49
     * @var array
50
     */
51
    protected $supportedMessages = [];
52
53
    /**
54
     * Set this to true if you want to be able to add any message you want.
55
     *
56
     * @var bool
57
     */
58
    protected $supportsAllMessages = false;
59
60
    /**
61
     * Contains the original form instance.
62
     *
63
     * @var FormInterface
64
     */
65
    protected $form;
66
67
    /**
68
     * Contains the merge of the supported messages and the TypoScript defined
69
     * messages.
70
     *
71
     * @var array
72
     */
73
    protected $messages = [];
74
75
    /**
76
     * Array of arbitral data which can be added by child classes, and will
77
     * then be added to the `$validationData` property of the form instance.
78
     *
79
     * @var array
80
     */
81
    protected $validationData = [];
82
83
    /**
84
     * @var ValidatorDataObject
85
     */
86
    protected $dataObject;
87
88
    /**
89
     * Constructs the validator, sets validation options and messages.
90
     *
91
     * @param array               $options Options for the validator.
92
     * @param ValidatorDataObject $dataObject
93
     */
94
    final public function __construct(array $options = [], ValidatorDataObject $dataObject)
95
    {
96
        parent::__construct($options);
97
98
        $this->dataObject = $dataObject;
99
        $this->form = $dataObject->getFormObject()->getForm();
100
    }
101
102
    /**
103
     * @param mixed $value
104
     * @return Result
105
     */
106
    public function validate($value)
107
    {
108
        /*
109
         * Messages are initialized just before the validation actually runs,
110
         * and not in the constructor.
111
         *
112
         * This allows more flexibility for the messages initialization; for
113
         * instance you can dynamically build the messages list in the method
114
         * `initializeObject()` of your validator (and not only in the class
115
         * variable declaration), then the messages will be processed just
116
         * below.
117
         */
118
        $this->messages = MessageService::get()->filterMessages(
119
            $this->dataObject->getValidation()->getMessages(),
120
            $this->supportedMessages,
121
            (bool)$this->supportsAllMessages
122
        );
123
124
        return parent::validate($value);
125
    }
126
127
    /**
128
     * Creates a new validation error and adds it to the result.
129
     *
130
     * @param string $key
131
     * @param int    $code
132
     * @param array  $arguments
133
     * @param string $title
134
     */
135
    protected function addError($key, $code, array $arguments = [], $title = '')
136
    {
137
        $message = $this->addMessage(Error::class, $key, $code, $arguments, $title);
138
        $this->result->addError($message);
139
    }
140
141
    /**
142
     * Creates a new validation warning and adds it to the result.
143
     *
144
     * @param string $key
145
     * @param int    $code
146
     * @param array  $arguments
147
     * @param string $title
148
     */
149
    protected function addWarning($key, $code, array $arguments = [], $title = '')
150
    {
151
        $message = $this->addMessage(Warning::class, $key, $code, $arguments, $title);
152
        $this->result->addWarning($message);
153
    }
154
155
    /**
156
     * Creates a new validation notice and adds it to the result.
157
     *
158
     * @param string $key
159
     * @param int    $code
160
     * @param array  $arguments
161
     * @param string $title
162
     */
163
    protected function addNotice($key, $code, array $arguments = [], $title = '')
164
    {
165
        $message = $this->addMessage(Notice::class, $key, $code, $arguments, $title);
166
        $this->result->addNotice($message);
167
    }
168
169
    /**
170
     * Get the full validation data.
171
     *
172
     * @return array
173
     */
174
    public function getValidationData()
175
    {
176
        return $this->validationData;
177
    }
178
179
    /**
180
     * Refreshes entirely the validation data (see `setValidationDataValue()`).
181
     *
182
     * @param array $validationData
183
     */
184
    protected function setValidationData(array $validationData)
185
    {
186
        $this->validationData = array_merge($this->validationData, $validationData);
187
    }
188
189
    /**
190
     * Adds an arbitral value to the validator, which will be added to the
191
     * `$validationData` property of the form.
192
     *
193
     * @param string $key   Key of the data.
194
     * @param mixed  $value Value bound to the key.
195
     */
196
    protected function setValidationDataValue($key, $value)
197
    {
198
        $this->validationData[$key] = $value;
199
    }
200
201
    /**
202
     * @param string $type
203
     * @param string $key
204
     * @param string $code
205
     * @param array  $arguments
206
     * @param string $title
207
     * @return mixed
208
     * @throws EntryNotFoundException
209
     */
210
    private function addMessage($type, $key, $code, array $arguments, $title)
211
    {
212
        if (!isset($this->messages[$key])) {
213
            throw EntryNotFoundException::errorKeyNotFoundForValidator($key, $this);
214
        }
215
216
        return new $type(
217
            $this->getMessage($key, $arguments),
218
            $code,
219
            $this->dataObject->getValidation()->getName(),
220
            $key,
221
            [],
222
            $title
223
        );
224
    }
225
226
    /**
227
     * This function should *always* be used when a message should be translated
228
     * when an error occurs in the validation process.
229
     *
230
     * @param  string $key       The key of the message, usually "default".
231
     * @param  array  $arguments Arguments given to the message.
232
     * @return string
233
     */
234
    private function getMessage($key, array $arguments = [])
235
    {
236
        return MessageService::get()->parseMessageArray($this->messages[$key], $arguments);
237
    }
238
239
    /**
240
     * @return array
241
     */
242
    public static function getJavaScriptValidationFiles()
243
    {
244
        return static::$javaScriptValidationFiles;
245
    }
246
}
247