Completed
Push — feature/middleware ( 864c18 )
by Romain
03:21
created

StepFetchingMiddleware::before()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 10
nc 4
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\Middleware\Item\Step;
15
16
use Romm\Formz\Form\Definition\Step\Step\Step;
17
use Romm\Formz\Middleware\Argument\Arguments;
18
use Romm\Formz\Middleware\Item\AbstractMiddleware;
19
use Romm\Formz\Middleware\Item\FormValidation\FormValidationSignal;
20
use Romm\Formz\Middleware\Item\Step\Service\StepMiddlewareService;
21
use Romm\Formz\Middleware\Signal\Before;
22
23
/**
24
 * This middleware will fetch the current step in the form, based on the request
25
 * context and the steps definition in the form configuration.
26
 *
27
 * It will check if the user has the right to stand on this step; if not, a loop
28
 * on all previous steps is done to determine the first valid step: the request
29
 * is then redirected to this step.
30
 */
31
class StepFetchingMiddleware extends AbstractMiddleware implements Before, FormValidationSignal
32
{
33
    /**
34
     * @var int
35
     */
36
    protected $priority = self::PRIORITY_STEP;
37
38
    /**
39
     * @var StepMiddlewareService
40
     */
41
    protected $service;
42
43
    /**
44
     * Inject the step service.
45
     */
46
    public function initializeMiddleware()
47
    {
48
        $this->service = StepMiddlewareService::get();
49
        $this->service->reset($this->getFormObject());
50
    }
51
52
    /**
53
     * @see StepFetchingMiddleware
54
     *
55
     * @param Arguments $arguments
56
     */
57
    public function before(Arguments $arguments)
58
    {
59
        $formObject = $this->getFormObject();
60
61
        if (false === $formObject->getDefinition()->hasSteps()) {
62
            return;
63
        }
64
65
        $currentStep = $this->getCurrentStep();
66
67
        if ($currentStep
68
            && false === $this->service->stepIsValid($currentStep)
69
        ) {
70
            /*
71
             * The user has no right to stand on the current step, a previous
72
             * valid step is determined, and the user is redirected to it.
73
             */
74
            $stepToRedirect = $this->service->getFirstInvalidStep($currentStep);
75
76
            if ($stepToRedirect instanceof Step) {
77
                $this->service->redirectToStep($stepToRedirect, $this->redirect());
78
            }
79
        }
80
    }
81
}
82