Completed
Push — wip/steps ( c05a56...a944ff )
by Romain
02:56
created

SkipViewHelper::initializeArguments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
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\ViewHelpers\Step;
15
16
use Exception;
17
use Romm\Formz\Exceptions\ContextNotFoundException;
18
use Romm\Formz\Form\Definition\Step\Step\Step;
19
use Romm\Formz\Service\ViewHelper\Form\FormViewHelperService;
20
use Romm\Formz\ViewHelpers\FormViewHelper;
21
use TYPO3\CMS\Extbase\Mvc\Web\Request;
22
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
23
use TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormFieldViewHelper;
24
25
class SkipViewHelper extends AbstractFormFieldViewHelper
26
{
27
    /**
28
     * @var string
29
     */
30
    protected $tagName = 'input';
31
32
    /**
33
     * @var FormViewHelperService
34
     */
35
    protected $formService;
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function initializeArguments()
41
    {
42
        parent::initializeArguments();
43
44
        $this->registerUniversalTagAttributes();
45
46
        $this->registerArgument('substep', 'string', 'Identifier of the optional substep to be skipped.');
47
    }
48
49
    /**
50
     * @return string
51
     */
52
    public function render(): string
53
    {
54
        /*
55
        * First, we check if this view helper is called from within the
56
        * `FormViewHelper`, because it would not make sense anywhere else.
57
        */
58
        if (false === $this->formService->formContextExists()) {
59
            throw ContextNotFoundException::skipViewHelperFormContextNotFound();
60
        }
61
62
        $formObject = $this->formService->getFormObject();
63
        $formDefinition = $formObject->getDefinition();
64
65
        if (false === $formDefinition->hasSteps()) {
66
            throw new Exception('No stop for this form.');
67
        }
68
69
        /** @var Request $request */
70
        $request = $this->controllerContext->getRequest();
71
        $currentStep = $formObject->fetchCurrentStep($request)->getCurrentStep();
72
73
        if ($substep = $this->arguments['substep'] ?? null) {
74
            if (false === $currentStep->hasSubsteps()) {
75
                throw new Exception('No substeps for this form.');
76
            }
77
78
            $substeps = $currentStep->getSubsteps();
79
80
            if (false === $substeps->hasEntry($substep)) {
81
                throw new Exception("No substep `$substep` for this form.");
82
            }
83
84
            $this->tag->addAttribute('fz-substep', $substep);
85
        }
86
87
        $this->tag->addAttribute('type', 'submit');
88
        $this->tag->addAttribute('value', $this->getValueAttribute());
89
        $this->tag->addAttribute('formaction', $this->formAction($currentStep));
0 ignored issues
show
Bug introduced by
It seems like $currentStep defined by $formObject->fetchCurren...uest)->getCurrentStep() on line 71 can be null; however, Romm\Formz\ViewHelpers\S...iewHelper::formAction() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
90
91
        return $this->tag->render();
92
    }
93
94
    private function formAction(Step $step): string
95
    {
96
        $formArguments = $this->viewHelperVariableContainer->get(FormViewHelper::class, 'arguments');
97
98
        $pageUid = (int)$formArguments['pageUid'] > 0 ? (int)$formArguments['pageUid'] : null;
99
100
        /** @var UriBuilder $uriBuilder */
101
        $uriBuilder = $this->renderingContext->getControllerContext()->getUriBuilder();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TYPO3Fluid\Fluid\Core\Re...nderingContextInterface as the method getControllerContext() does only exist in the following implementations of said interface: Nimut\TestingFramework\R...RenderingContextFixture, TYPO3\CMS\Fluid\Core\Rendering\RenderingContext, TYPO3\CMS\Fluid\Tests\Un...RenderingContextFixture.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
102
103
        $arguments = (array)$formArguments['arguments'];
104
105
        $arguments['skip'] = true;
106
        $arguments['step'] = $step->getIdentifier();
107
108
        $substep = $this->arguments['substep'] ?? null;
109
110
        if ($substep) {
111
            $arguments['skipSubsteps'] = $substep;
112
        }
113
114
        return $uriBuilder
115
            ->reset()
116
            ->setTargetPageUid($pageUid)
117
            ->setTargetPageType($formArguments['pageType'])
118
            ->setNoCache($formArguments['noCache'])
119
            ->setUseCacheHash(!$formArguments['noCacheHash'])
120
            ->setSection($formArguments['section'])
121
            ->setCreateAbsoluteUri($formArguments['absolute'])
122
            ->setArguments((array)$formArguments['additionalParams'])
123
            ->setAddQueryString($formArguments['addQueryString'])
124
            ->setAddQueryStringMethod($formArguments['addQueryStringMethod'])
125
            ->setArgumentsToBeExcludedFromQueryString((array)$formArguments['argumentsToBeExcludedFromQueryString'])
126
            ->setFormat($formArguments['format'])
127
            ->uriFor(
128
                $formArguments['action'],
129
                $arguments,
130
                $formArguments['controller'],
131
                $formArguments['extensionName'],
132
                $formArguments['pluginName']
133
            );
134
    }
135
136
    /**
137
     * @param FormViewHelperService $service
138
     */
139
    public function injectFormService(FormViewHelperService $service)
140
    {
141
        $this->formService = $service;
142
    }
143
}
144