Completed
Push — middleware-wip ( 17e892...bf36ad )
by Romain
02:41
created

FormValidationMiddleware::process()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 15
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\Middleware\Item\FormValidation;
15
16
use Romm\Formz\Configuration\Form\Field\Field;
17
use Romm\Formz\Middleware\Item\FieldValidation\FieldValidationArguments;
18
use Romm\Formz\Middleware\Item\FieldValidation\FieldValidationSignal;
19
use Romm\Formz\Middleware\Item\OnBeginMiddleware;
20
use Romm\Formz\Middleware\Signal\SendsMiddlewareSignal;
21
use Romm\Formz\Validation\Validator\Form\MiddlewareFormValidator;
22
23
/**
24
 * This middleware takes care of validating the form instance, with a proper
25
 * form validator instance.
26
 *
27
 * You can bind middlewares to the signal `FormValidationSignal`, which will be
28
 * dispatched if and only if the form was submitted by the user.
29
 */
30
class FormValidationMiddleware extends OnBeginMiddleware implements SendsMiddlewareSignal
31
{
32
    /**
33
     * @var \Romm\Formz\Middleware\Item\FormValidation\FormValidationOptionDefinition
34
     */
35
    protected $options;
36
37
    /**
38
     * @see FormValidationMiddleware
39
     */
40
    protected function process()
41
    {
42
        $formObject = $this->getFormObject();
43
44
        if ($formObject->hasForm()
45
            && $formObject->formWasSubmitted()
46
        ) {
47
            $this->beforeSignal(FormValidationSignal::class)->dispatch();
48
49
            $callback = function (Field $field) {
50
                $this->afterSignal(FieldValidationSignal::class)
51
                    ->withArguments(new FieldValidationArguments($field))
52
                    ->dispatch();
53
            };
54
55
            $validator = new MiddlewareFormValidator(
56
                ['name' => $formObject->getName()],
57
                $callback
58
            );
59
            $validator->setResult($this->getResult());
60
            $validator->validate($formObject->getForm());
61
62
            $this->afterSignal(FormValidationSignal::class)->dispatch();
63
        }
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    public function getAllowedSignals()
70
    {
71
        return [FormValidationSignal::class, FieldValidationSignal::class];
72
    }
73
}
74