Completed
Push — wip/steps ( 6fd1d1...f0b9ec )
by Romain
30:46
created

FocusLinkViewHelper::getFormObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
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\ViewHelpers\Field;
15
16
use Romm\Formz\Core\Core;
17
use Romm\Formz\Exceptions\ContextNotFoundException;
18
use Romm\Formz\Form\Definition\Field\Field;
19
use Romm\Formz\Form\Definition\Step\Step\Step;
20
use Romm\Formz\Form\FormInterface;
21
use Romm\Formz\Form\FormObject\FormObject;
22
use Romm\Formz\Form\FormObject\FormObjectFactory;
23
use Romm\Formz\Middleware\Item\Field\Focus\FieldFocusMiddleware;
24
use Romm\Formz\Service\ViewHelper\Form\FormViewHelperService;
25
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
26
27
/**
28
 * @todo
29
 */
30
class FocusLinkViewHelper extends AbstractTagBasedViewHelper
31
{
32
    /**
33
     * @var string
34
     */
35
    protected $tagName = 'a';
36
37
    /**
38
     * @var FormViewHelperService
39
     */
40
    protected $formService;
41
42
    /**
43
     * Arguments initialization: does also use universal tags.
44
     */
45
    public function initializeArguments()
46
    {
47
        $this->registerUniversalTagAttributes();
48
49
        $this->registerArgument('field', 'string', 'Name of the field.', true);
50
        $this->registerArgument('form', FormInterface::class, '@todo.'); // @todo
51
        $this->registerArgument('step', 'string', 'Identifier of the step, if the field is present of several steps.');
52
        $this->registerArgument('additionalParams', 'array', 'Additional parameters passed to the URI.', false, []);
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function render()
59
    {
60
        $this->checkFormContext();
61
        $this->checkFieldExists();
62
63
        $this->tag->addAttribute('href', $this->getUri());
64
        $this->tag->setContent($this->renderChildren());
65
        $this->tag->forceClosingTag(true);
66
67
        return $this->tag->render();
68
    }
69
70
    /**
71
     * Builds and returns the URI to the given step, and adds parameters that
72
     * will allow the system to understand which field to edit.
73
     *
74
     * @return string
75
     */
76
    protected function getUri()
77
    {
78
        $pageUid = null;
79
        $action = null;
80
        $controller = null;
81
        $extensionName = null;
82
83
        $step = $this->getStep();
84
85
        if ($step) {
86
            $request = $this->renderingContext->getControllerContext()->getRequest();
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...
87
88
            if (Core::get()->getPageController()->id !== $step->getPageUid()) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of \Romm\Formz\Core\Core::g...getPageController()->id (string) and $step->getPageUid() (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
89
                // @todo handle backend context
90
                $pageUid = $step->getPageUid();
91
            }
92
93
            if ($request->getControllerActionName() !== $step->getAction()) {
94
                $action = $step->getAction();
95
            }
96
97
            if ($request->getControllerName() !== $step->getController()) {
98
                $controller = $step->getController();
99
            }
100
101
            if ($request->getControllerExtensionName() !== $step->getExtension()) {
102
                $extensionName = $step->getExtension();
103
            }
104
        }
105
106
        $uriBuilder = $this->controllerContext->getUriBuilder();
107
        $uri = $uriBuilder->reset();
108
        $uri->setArguments($this->arguments['additionalParams']);
109
110
        if ($pageUid) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pageUid of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
111
            $uri->setTargetPageUid($pageUid);
112
        }
113
114
        return $uri->uriFor(
115
            $action,
116
            [FieldFocusMiddleware::FIELD_FOCUS_ARGUMENT => $this->getField()->getName()],
117
            $controller,
118
            $extensionName
119
        );
120
121
    }
122
123
    /**
124
     * Checks that the step name given to the view helper exists in the form
125
     * definition, and returns it.
126
     *
127
     * Will also check that the given field name is supported by the step.
128
     *
129
     * @return Step
130
     * @throws \Exception
131
     */
132
    protected function getStep()
133
    {
134
        $formDefinition = $this->getFormObject()->getDefinition();
135
        $stepIdentifier = $this->arguments['step'];
136
        $step = null;
137
138
        if ($stepIdentifier) {
139
            if (false === $formDefinition->getSteps()->hasEntry($stepIdentifier)) {
140
                throw new \Exception('@todo : the step "' . $stepIdentifier . '" does not exists.'); // @todo
141
            }
142
143
            $step = $formDefinition->getSteps()->getEntry($stepIdentifier);
144
            $field = $this->getField();
145
146
            if (false === $step->supportsField($field)) {
147
                throw new \Exception('@todo : the step "' . $step->getIdentifier() . '" does not support the field "' . $field->getName() . '".'); // @todo
148
            }
149
        } else {
150
            foreach ($formDefinition->getSteps()->getEntries() as $stepEntry) {
151
                if ($stepEntry->supportsField($this->getField())) {
152
                    $step = $stepEntry;
153
                    break;
154
                }
155
            }
156
        }
157
158
        return $step;
159
    }
160
161
    /**
162
     * @throws ContextNotFoundException
163
     */
164
    protected function checkFormContext()
165
    {
166
        if (null === $this->getForm()
167
            && false === $this->formService->formContextExists()
168
        ) {
169
            throw new ContextNotFoundException('form context not found'); // @todo
170
        }
171
    }
172
173
    /**
174
     * Checks that the given field name exists in the form definition.
175
     */
176
    protected function checkFieldExists()
177
    {
178
        $formDefinition = $this->getFormObject()->getDefinition();
179
        $fieldName = $this->arguments['field'];
180
181
        if (false === $formDefinition->hasField($fieldName)) {
182
            throw new \Exception('field not found : ' . $fieldName); // @todo
183
        }
184
    }
185
186
    /**
187
     * Returns the field instance from the argument given to the view helper.
188
     *
189
     * @return Field
190
     */
191
    protected function getField()
192
    {
193
        return $this->getFormObject()
194
            ->getDefinition()
195
            ->getField($this->arguments['field']);
196
    }
197
198
    /**
199
     * @return FormObject
200
     */
201
    protected function getFormObject()
202
    {
203
        return $this->formService->formContextExists()
204
            ? $this->formService->getFormObject()
205
            : FormObjectFactory::get()->getInstanceWithFormInstance($this->getForm());
206
    }
207
208
    /**
209
     * @return FormInterface|null
210
     */
211
    protected function getForm()
212
    {
213
        return $this->formService->formContextExists()
214
            ? $this->formService->getFormObject()->getForm()
215
            : $this->arguments['form'];
216
    }
217
218
    /**
219
     * @param FormViewHelperService $service
220
     */
221
    public function injectFormService(FormViewHelperService $service)
222
    {
223
        $this->formService = $service;
224
    }
225
}
226