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

FormValidationMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
lcom 1
cbo 5
dl 0
loc 39
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B process() 0 25 3
A getAllowedSignals() 0 4 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\Middleware\Items\FormValidation;
15
16
use Romm\Formz\Configuration\Form\Field\Field;
17
use Romm\Formz\Middleware\Items\FieldValidation\FieldValidationArguments;
18
use Romm\Formz\Middleware\Items\FieldValidation\FieldValidationSignal;
19
use Romm\Formz\Middleware\Items\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
     * @see FormValidationMiddleware
34
     */
35
    protected function process()
36
    {
37
        $formObject = $this->getFormObject();
38
39
        if ($formObject->hasForm()
40
            && $formObject->formWasSubmitted()
41
        ) {
42
            $this->beforeSignal(FormValidationSignal::class)->dispatch();
43
44
            $callback = function (Field $field) {
45
                $this->afterSignal(FieldValidationSignal::class)
46
                    ->withArguments(new FieldValidationArguments($field))
47
                    ->dispatch();
48
            };
49
50
            $validator = new MiddlewareFormValidator(
51
                ['name' => $formObject->getName()],
52
                $callback
53
            );
54
            $validator->setResult($this->getResult());
55
            $validator->validate($formObject->getForm());
56
57
            $this->afterSignal(FormValidationSignal::class)->dispatch();
58
        }
59
    }
60
61
    /**
62
     * @return array
63
     */
64
    public function getAllowedSignals()
65
    {
66
        return [FormValidationSignal::class, FieldValidationSignal::class];
67
    }
68
}
69