Completed
Push — middleware-wip ( aa44a7...fcef97 )
by Romain
03:00
created

AbstractFormValidator::getResult()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
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\Configuration\Form\Field\Field;
17
use Romm\Formz\Core\Core;
18
use Romm\Formz\Error\FormResult;
19
use Romm\Formz\Exceptions\InvalidArgumentTypeException;
20
use Romm\Formz\Form\FormInterface;
21
use Romm\Formz\Form\FormObject\FormObject;
22
use Romm\Formz\Form\FormObject\FormObjectFactory;
23
use Romm\Formz\Service\FormService;
24
use Romm\Formz\Validation\Validator\Form\DataObject\FormValidatorDataObject;
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
     * @var FormValidatorDataObject
104
     */
105
    protected $dataObject;
106
107
    /**
108
     * Initializes all class variables.
109
     *
110
     * @param FormInterface $form
111
     * @throws InvalidArgumentTypeException
112
     */
113
    protected function initializeValidator($form)
114
    {
115
        if (false === $form instanceof FormInterface) {
116
            throw InvalidArgumentTypeException::validatingWrongFormType(get_class($form));
117
        }
118
119
        $this->form = $form;
120
        $this->formObject = FormObjectFactory::get()->getInstanceFromFormInstance($this->form, $this->options['name']);
121
        $this->formValidatorExecutor = $this->getFormValidatorExecutor();
122
        $this->result = $this->formObject->getFormResult();
123
124
        $this->getDataObject()->addFieldValidationCallback(function (Field $field) {
125
            $this->afterFieldValidation($field);
126
        });
127
    }
128
129
    /**
130
     * Checks the given form instance, and launches the validation if it is a
131
     * correct form.
132
     *
133
     * @param FormInterface $form The form instance to be validated.
134
     * @return FormResult
135
     */
136
    public function validate($form)
137
    {
138
        $this->initializeValidator($form);
139
140
        $proxy = FormObjectFactory::get()->getProxy($this->formObject, $form);
141
        $proxy->markFormAsValidated();
142
        $proxy->markFormAsSubmitted();
143
144
        $this->isValid($form);
145
146
        return $this->result;
147
    }
148
149
    /**
150
     * Runs the whole validation workflow.
151
     *
152
     * @param FormInterface $form
153
     */
154
    final public function isValid($form)
155
    {
156
        $this->formValidatorExecutor->applyBehaviours();
157
        $this->formValidatorExecutor->checkFieldsActivation();
158
159
        $this->beforeValidationProcess();
160
161
        $this->formValidatorExecutor->validateFields();
162
163
        $this->afterValidationProcess();
164
165
        if ($this->result->hasErrors()) {
166
            // Storing the form for possible third party further usage.
167
            FormService::addFormWithErrors($form);
168
        }
169
    }
170
171
    /**
172
     * Override this function in your child class to handle some pre-validation
173
     * process.
174
     */
175
    protected function beforeValidationProcess()
176
    {
177
    }
178
179
    /**
180
     * Override this function in your child class to handle some post-validation
181
     * process.
182
     */
183
    protected function afterValidationProcess()
184
    {
185
    }
186
187
    /**
188
     * After each field has been validated, a matching method can be called if
189
     * it exists in the child class.
190
     *
191
     * The syntax is `{lowerCamelCaseFieldName}Validated()`.
192
     *
193
     * Example: for field `firstName` - `firstNameValidated()`.
194
     *
195
     * @param Field $field
196
     */
197
    protected function afterFieldValidation(Field $field)
198
    {
199
        $functionName = lcfirst($field->getName() . 'Validated');
200
201
        if (method_exists($this, $functionName)) {
202
            call_user_func([$this, $functionName]);
203
        }
204
    }
205
206
    /**
207
     * @return FormValidatorExecutor
208
     */
209
    protected function getFormValidatorExecutor()
210
    {
211
        /** @var FormValidatorExecutor $formValidatorExecutor */
212
        $formValidatorExecutor = Core::instantiate(FormValidatorExecutor::class, $this->formObject, $this->getDataObject());
213
214
        return $formValidatorExecutor;
215
    }
216
217
    /**
218
     * @return FormValidatorDataObject
219
     */
220
    public function getDataObject()
221
    {
222
        if (null === $this->dataObject) {
223
            $this->dataObject = Core::instantiate(FormValidatorDataObject::class);
224
        }
225
226
        return $this->dataObject;
227
    }
228
}
229