Completed
Push — unit-tests-validation ( 736ebb...389d28 )
by Romain
02:13
created

AbstractFormValidator::isValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
rs 9.3142
cc 2
eloc 11
nc 2
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\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\Service\FormService;
22
use TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator as ExtbaseAbstractValidator;
23
24
/**
25
 * This is the abstract form validator, which must be inherited by any custom
26
 * form validator in order to work properly.
27
 *
28
 * Please note that a default form validator already exists if you need a form
29
 * which does not require any particular action: `DefaultFormValidator`.
30
 *
31
 * A form validator should be called to validate any form instance (which is a
32
 * child of `AbstractForm`). Usually, this is used in controller actions to
33
 * validate a form sent by the user. Example:
34
 *
35
 * /**
36
 *  * Action called when the Example form is submitted.
37
 *  *
38
 *  * @param $exForm
39
 *  * @validate $exForm Romm.Formz:Form\DefaultFormValidator
40
 *  * /
41
 *  public function submitFormAction(ExampleForm $exForm) { ... }
42
 *
43
 *******************************************************************************
44
 *
45
 * You may use you own custom form validator in order to be able to use the
46
 * following features:
47
 *
48
 * - Pre-validation custom process:
49
 *   By extending the method `beforeValidationProcess()`, you are able to handle
50
 *   anything you want just before the form validation begins to loop on every
51
 *   field. This can be used for instance to (de)activate the validation of
52
 *   certain fields under very specific circumstances.
53
 *
54
 * - In real time custom process:
55
 *   After each field went trough a validation process, a magic method is called
56
 *   to allow very low level custom process. The magic method name looks like:
57
 *   "{lowerCamelCaseFieldName}Validated". For instance, when the "email" field
58
 *   just went trough the validation process, the method `emailValidated()` is
59
 *   called.
60
 *
61
 * - Post-validation custom process:
62
 *   After the validation was done on every field of the form, this method is
63
 *   called to allow you high level process. For instance, let's assume your
64
 *   form is used to calculate a price estimation depending on information
65
 *   submitted in the form; when the form went trough the validation process and
66
 *   got no error, you can run the price estimation, and if any error occurs you
67
 *   are still able to add an error to `$this->result` (in a controller you do
68
 *   not have access to it anymore).
69
 */
70
abstract class AbstractFormValidator extends ExtbaseAbstractValidator implements FormValidatorInterface
71
{
72
    /**
73
     * @inheritdoc
74
     */
75
    protected $supportedOptions = [
76
        'name' => ['', 'Name of the form.', 'string', true]
77
    ];
78
79
    /**
80
     * @var FormResult
81
     */
82
    protected $result;
83
84
    /**
85
     * Contains the validation results of all forms which were validated. The
86
     * key is the form name (the property `formName` in the form configuration)
87
     * and the value is an instance of `FormResult`.
88
     *
89
     * Note: we need to store the results here, because the TYPO3 request
90
     * handler builds an instance of Extbase's `Result` from scratch, so we are
91
     * not able to retrieve the `FormResult` instance afterward.
92
     *
93
     * @var FormResult[]
94
     */
95
    private static $formsValidationResults = [];
96
97
    /**
98
     * Checks the given form instance, and launches the validation if it is a
99
     * correct form.
100
     *
101
     * @param FormInterface $form The form instance to be validated.
102
     * @return FormResult
103
     * @throws InvalidArgumentTypeException
104
     */
105
    final public function validate($form)
106
    {
107
        if (false === $form instanceof FormInterface) {
108
            throw new InvalidArgumentTypeException(
109
                'Trying to validate a form that does not implement the interface "' . FormInterface::class . '". Given class: "' . get_class($form) . '"',
110
                1487865158
111
            );
112
        }
113
114
        $this->result = new FormResult;
115
116
        $this->isValid($form);
117
118
        return $this->result;
119
    }
120
121
    /**
122
     * Runs the whole validation workflow.
123
     *
124
     * @param FormInterface $form
125
     */
126
    final public function isValid($form)
127
    {
128
        $formValidatorExecutor = $this->getFormValidatorExecutor($form);
129
        $formValidatorExecutor->applyBehaviours();
130
        $formValidatorExecutor->checkFieldsActivation();
131
132
        $this->beforeValidationProcess();
133
134
        $formValidatorExecutor->validateFields(function (Field $field) {
135
            $this->callAfterFieldValidationMethod($field);
136
        });
137
138
        $this->afterValidationProcess();
139
140
        if ($this->result->hasErrors()) {
141
            // Storing the form for possible third party further usage.
142
            FormService::addFormWithErrors($form);
143
        }
144
145
        self::$formsValidationResults[get_class($form) . '::' . $this->options['name']] = $this->result;
146
    }
147
148
    /**
149
     * Use this function to (de)activate the validation for some given fields.
150
     */
151
    protected function beforeValidationProcess()
152
    {
153
    }
154
155
    /**
156
     * Use this function to run your own processes after the validation ran.
157
     */
158
    protected function afterValidationProcess()
159
    {
160
    }
161
162
    /**
163
     * After each field has been validated, a matching method can be called if
164
     * it exists in the child class.
165
     *
166
     * The syntax is `{lowerCamelCaseFieldName}Validated()`.
167
     *
168
     * Example: for field `firstName` - `firstNameValidated()`.
169
     *
170
     * @param Field $field
171
     */
172
    private function callAfterFieldValidationMethod(Field $field)
173
    {
174
        $functionName = lcfirst($field->getFieldName() . 'Validated');
175
176
        if (method_exists($this, $functionName)) {
177
            call_user_func([$this, $functionName]);
178
        }
179
    }
180
181
    /**
182
     * Returns the validation result of the asked form. The form name matches
183
     * the property `formName` of the form configuration.
184
     *
185
     * @param string $formClassName
186
     * @param string $formName
187
     * @return null|FormResult
188
     */
189
    public static function getFormValidationResult($formClassName, $formName)
190
    {
191
        $key = $formClassName . '::' . $formName;
192
193
        return (true === isset(self::$formsValidationResults[$key]))
194
            ? self::$formsValidationResults[$key]
195
            : null;
196
    }
197
198
    /**
199
     * @param FormInterface $form
200
     * @return FormValidatorExecutor
201
     */
202
    protected function getFormValidatorExecutor(FormInterface $form)
203
    {
204
        /** @var FormValidatorExecutor $formValidatorExecutor */
205
        $formValidatorExecutor = Core::instantiate(FormValidatorExecutor::class, $form, $this->options['name'], $this->result);
206
207
        return $formValidatorExecutor;
208
    }
209
}
210