Completed
Push — tmp ( 2c4763...a47a14 )
by Romain
02:07
created

AbstractValidator::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
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, then they will be processed
115
         * just below.
116
         */
117
        $this->messages = MessageService::get()->filterMessages(
118
            $this->dataObject->getValidation()->getMessages(),
119
            $this->supportedMessages,
120
            (bool)$this->supportsAllMessages
121
        );
122
123
        return parent::validate($value);
124
    }
125
126
    /**
127
     * Creates a new validation error and adds it to the result.
128
     *
129
     * @param string $key
130
     * @param int    $code
131
     * @param array  $arguments
132
     * @param string $title
133
     */
134
    protected function addError($key, $code, array $arguments = [], $title = '')
135
    {
136
        $message = $this->addMessage(Error::class, $key, $code, $arguments, $title);
137
        $this->result->addError($message);
138
    }
139
140
    /**
141
     * Creates a new validation warning and adds it to the result.
142
     *
143
     * @param string $key
144
     * @param int    $code
145
     * @param array  $arguments
146
     * @param string $title
147
     */
148
    protected function addWarning($key, $code, array $arguments = [], $title = '')
149
    {
150
        $message = $this->addMessage(Warning::class, $key, $code, $arguments, $title);
151
        $this->result->addWarning($message);
152
    }
153
154
    /**
155
     * Creates a new validation notice and adds it to the result.
156
     *
157
     * @param string $key
158
     * @param int    $code
159
     * @param array  $arguments
160
     * @param string $title
161
     */
162
    protected function addNotice($key, $code, array $arguments = [], $title = '')
163
    {
164
        $message = $this->addMessage(Notice::class, $key, $code, $arguments, $title);
165
        $this->result->addNotice($message);
166
    }
167
168
    /**
169
     * Get the full validation data.
170
     *
171
     * @return array
172
     */
173
    public function getValidationData()
174
    {
175
        return $this->validationData;
176
    }
177
178
    /**
179
     * Refreshes entirely the validation data (see `setValidationDataValue()`).
180
     *
181
     * @param array $validationData
182
     */
183
    protected function setValidationData(array $validationData)
184
    {
185
        $this->validationData = array_merge($this->validationData, $validationData);
186
    }
187
188
    /**
189
     * Adds an arbitral value to the validator, which will be added to the
190
     * `$validationData` property of the form.
191
     *
192
     * @param string $key   Key of the data.
193
     * @param mixed  $value Value bound to the key.
194
     */
195
    protected function setValidationDataValue($key, $value)
196
    {
197
        $this->validationData[$key] = $value;
198
    }
199
200
    /**
201
     * @param string $type
202
     * @param string $key
203
     * @param string $code
204
     * @param array  $arguments
205
     * @param string $title
206
     * @return mixed
207
     * @throws EntryNotFoundException
208
     */
209
    private function addMessage($type, $key, $code, array $arguments, $title)
210
    {
211
        if (!isset($this->messages[$key])) {
212
            throw EntryNotFoundException::errorKeyNotFoundForValidator($key, $this);
213
        }
214
215
        return new $type(
216
            $this->getMessage($key, $arguments),
217
            $code,
218
            $this->dataObject->getValidation()->getName(),
219
            $key,
220
            [],
221
            $title
222
        );
223
    }
224
225
    /**
226
     * This function should *always* be used when a message should be translated
227
     * when an error occurs in the validation process.
228
     *
229
     * @param  string $key       The key of the message, usually "default".
230
     * @param  array  $arguments Arguments given to the message.
231
     * @return string
232
     */
233
    private function getMessage($key, array $arguments = [])
234
    {
235
        return MessageService::get()->parseMessageArray($this->messages[$key], $arguments);
236
    }
237
238
    /**
239
     * @return array
240
     */
241
    public static function getJavaScriptValidationFiles()
242
    {
243
        return static::$javaScriptValidationFiles;
244
    }
245
}
246