Completed
Push — feature/improve-form-definitio... ( ef7fcf...737532 )
by Romain
04:37
created

AbstractFormValidator::getProxy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
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\Form;
15
16
use Romm\Formz\Core\Core;
17
use Romm\Formz\Error\FormResult;
18
use Romm\Formz\Exceptions\InvalidArgumentTypeException;
19
use Romm\Formz\Form\Definition\Field\Field;
20
use Romm\Formz\Form\FormInterface;
21
use Romm\Formz\Form\FormObject\FormObject;
22
use Romm\Formz\Form\FormObject\FormObjectFactory;
23
use Romm\Formz\Form\FormObject\FormObjectProxy;
24
use Romm\Formz\Service\FormService;
25
use TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator as ExtbaseAbstractValidator;
26
27
/**
28
 * This is the abstract form validator, which must be inherited by any custom
29
 * form validator in order to work properly.
30
 *
31
 * Please note that a default form validator already exists if you need a form
32
 * which does not require any particular action: `DefaultFormValidator`.
33
 *
34
 * A form validator should be called to validate any form instance (which is a
35
 * child of `AbstractForm`). Usually, this is used in controller actions to
36
 * validate a form sent by the user. Example:
37
 *
38
 * /**
39
 *  * Action called when the Example form is submitted.
40
 *  *
41
 *  * @param $exForm
42
 *  * @validate $exForm Romm.Formz:Form\DefaultFormValidator
43
 *  * /
44
 *  public function submitFormAction(ExampleForm $exForm) { ... }
45
 *
46
 *******************************************************************************
47
 *
48
 * You may use you own custom form validator in order to be able to use the
49
 * following features:
50
 *
51
 * - Pre-validation custom process:
52
 *   By extending the method `beforeValidationProcess()`, you are able to handle
53
 *   anything you want just before the form validation begins to loop on every
54
 *   field. This can be used for instance to (de)activate the validation of
55
 *   certain fields under very specific circumstances.
56
 *
57
 * - In real time custom process:
58
 *   After each field went trough a validation process, a magic method is called
59
 *   to allow very low level custom process. The magic method name looks like:
60
 *   "{lowerCamelCaseFieldName}Validated". For instance, when the "email" field
61
 *   just went trough the validation process, the method `emailValidated()` is
62
 *   called.
63
 *
64
 * - Post-validation custom process:
65
 *   After the validation was done on every field of the form, this method is
66
 *   called to allow you high level process. For instance, let's assume your
67
 *   form is used to calculate a price estimation depending on information
68
 *   submitted in the form; when the form went trough the validation process and
69
 *   got no error, you can run the price estimation, and if any error occurs you
70
 *   are still able to add an error to `$this->result` (in a controller you do
71
 *   not have access to it anymore).
72
 */
73
abstract class AbstractFormValidator extends ExtbaseAbstractValidator implements FormValidatorInterface
74
{
75
    /**
76
     * @inheritdoc
77
     */
78
    protected $supportedOptions = [
79
        'name' => ['', 'Name of the form.', 'string', true]
80
    ];
81
82
    /**
83
     * @var FormResult
84
     */
85
    protected $result;
86
87
    /**
88
     * @var FormInterface
89
     */
90
    protected $form;
91
92
    /**
93
     * @var FormObject
94
     */
95
    protected $formObject;
96
97
    /**
98
     * @var FormValidatorExecutor
99
     */
100
    private $formValidatorExecutor;
101
102
    /**
103
     * Initializes all class variables.
104
     *
105
     * @param FormInterface $form
106
     * @throws InvalidArgumentTypeException
107
     */
108
    protected function initializeValidator($form)
109
    {
110
        if (false === $form instanceof FormInterface) {
111
            throw InvalidArgumentTypeException::validatingWrongFormType(get_class($form));
112
        }
113
114
        $this->form = $form;
115
        $this->formObject = $this->getFormObject();
116
        $this->formValidatorExecutor = $this->getFormValidatorExecutor();
117
        $this->result = $this->formObject->getFormResult();
118
    }
119
120
    /**
121
     * Checks the given form instance, and launches the validation if it is a
122
     * correct form.
123
     *
124
     * @param FormInterface $form The form instance to be validated.
125
     * @return FormResult
126
     */
127
    final public function validate($form)
128
    {
129
        $this->initializeValidator($form);
130
131
        $proxy = $this->getProxy($form);
132
        $proxy->markFormAsValidated();
133
        $proxy->markFormAsSubmitted();
134
135
        $this->validateGhost($form, false);
136
137
        return $this->result;
138
    }
139
140
    /**
141
     * Validates the form, but wont save form data in the form object.
142
     *
143
     * @param FormInterface $form
144
     * @param bool          $initialize
145
     * @return FormResult
146
     * @internal
147
     */
148
    public function validateGhost($form, $initialize = true)
149
    {
150
        if ($initialize) {
151
            $this->initializeValidator($form);
152
        }
153
154
        $this->isValid($form);
155
156
        return $this->result;
157
    }
158
159
    /**
160
     * Runs the whole validation workflow.
161
     *
162
     * @param FormInterface $form
163
     */
164
    final public function isValid($form)
165
    {
166
        $this->formValidatorExecutor->applyBehaviours();
167
        $this->formValidatorExecutor->checkFieldsActivation();
168
169
        $this->beforeValidationProcess();
170
171
        $this->formValidatorExecutor->validateFields(function (Field $field) {
172
            $this->callAfterFieldValidationMethod($field);
173
        });
174
175
        $this->afterValidationProcess();
176
177
        if ($this->result->hasErrors()) {
178
            // Storing the form for possible third party further usage.
179
            FormService::addFormWithErrors($form);
180
        }
181
    }
182
183
    /**
184
     * Override this function in your child class to handle some pre-validation
185
     * process.
186
     */
187
    protected function beforeValidationProcess()
188
    {
189
    }
190
191
    /**
192
     * Override this function in your child class to handle some post-validation
193
     * process.
194
     */
195
    protected function afterValidationProcess()
196
    {
197
    }
198
199
    /**
200
     * After each field has been validated, a matching method can be called if
201
     * it exists in the child class.
202
     *
203
     * The syntax is `{lowerCamelCaseFieldName}Validated()`.
204
     *
205
     * Example: for field `firstName` - `firstNameValidated()`.
206
     *
207
     * @param Field $field
208
     */
209
    private function callAfterFieldValidationMethod(Field $field)
210
    {
211
        $functionName = lcfirst($field->getName() . 'Validated');
212
213
        if (method_exists($this, $functionName)) {
214
            call_user_func([$this, $functionName]);
215
        }
216
    }
217
218
    /**
219
     * @return FormValidatorExecutor
220
     */
221
    protected function getFormValidatorExecutor()
222
    {
223
        /** @var FormValidatorExecutor $formValidatorExecutor */
224
        $formValidatorExecutor = Core::instantiate(FormValidatorExecutor::class, $this->formObject, $this->options['name']);
225
226
        return $formValidatorExecutor;
227
    }
228
229
    /**
230
     * @return FormObject
231
     */
232
    protected function getFormObject()
233
    {
234
        return FormObjectFactory::get()->getInstanceWithFormInstance($this->form, $this->options['name']);
235
    }
236
237
    /**
238
     * @param FormInterface $form
239
     * @return FormObjectProxy
240
     */
241
    protected function getProxy(FormInterface $form)
242
    {
243
        return FormObjectFactory::get()->getProxy($form);
244
    }
245
}
246