Completed
Push — tmp ( 1b6860 )
by Romain
13:27 queued 11s
created

FieldViewHelper::getTemplateArguments()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
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;
15
16
use Romm\Formz\Configuration\View\Layouts\Layout;
17
use Romm\Formz\Configuration\View\View;
18
use Romm\Formz\Exceptions\ContextNotFoundException;
19
use Romm\Formz\Exceptions\EntryNotFoundException;
20
use Romm\Formz\Exceptions\InvalidArgumentTypeException;
21
use Romm\Formz\Exceptions\InvalidArgumentValueException;
22
use Romm\Formz\Exceptions\PropertyNotAccessibleException;
23
use Romm\Formz\Service\StringService;
24
use Romm\Formz\Service\ViewHelper\Field\FieldViewHelperService;
25
use Romm\Formz\Service\ViewHelper\Form\FormViewHelperService;
26
use Romm\Formz\Service\ViewHelper\Slot\SlotViewHelperService;
27
use TYPO3\CMS\Core\Utility\ArrayUtility;
28
use TYPO3\CMS\Core\Utility\GeneralUtility;
29
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
30
31
/**
32
 * This view helper is used to automatize the rendering of a field layout. It
33
 * will use the TypoScript properties at the path `config.tx_formz.view.layout`.
34
 *
35
 * You need to indicate the name of the field which will be rendered, and the
36
 * name of the layout which should be used (it must be present in the TypoScript
37
 * configuration).
38
 *
39
 * Example of layout: `bootstrap.3-cols`. You may indicate only the group, then
40
 * the name of the layout will be set to `default` (if you use the layout group
41
 * `bootstrap`, the layout `default` will be used, only if it does exist of
42
 * course).
43
 */
44
class FieldViewHelper extends AbstractViewHelper
45
{
46
    /**
47
     * @var bool
48
     */
49
    protected $escapeOutput = false;
50
51
    /**
52
     * @var array
53
     */
54
    public static $reservedVariablesNames = ['layout', 'formName', 'fieldName', 'fieldId'];
55
56
    /**
57
     * @var FormViewHelperService
58
     */
59
    protected $formService;
60
61
    /**
62
     * @var FieldViewHelperService
63
     */
64
    protected $fieldService;
65
66
    /**
67
     * @var SlotViewHelperService
68
     */
69
    protected $slotService;
70
71
    /**
72
     * @var array
73
     */
74
    protected $originalArguments = [];
75
76
    /**
77
     * @inheritdoc
78
     */
79
    public function initializeArguments()
80
    {
81
        $this->registerArgument('name', 'string', 'Name of the field which should be rendered.', true);
82
        $this->registerArgument('layout', 'string', 'Path of the TypoScript layout which will be used.', true);
83
        $this->registerArgument('arguments', 'array', 'Arbitrary arguments which will be sent to the field template.', false, []);
84
    }
85
86
    /**
87
     * @inheritdoc
88
     */
89
    public function render()
90
    {
91
        /*
92
         * First, we check if this view helper is called from within the
93
         * `FormViewHelper`, because it would not make sense anywhere else.
94
         */
95
        if (false === $this->formService->formContextExists()) {
96
            throw ContextNotFoundException::fieldViewHelperFormContextNotFound();
97
        }
98
99
        /*
100
         * Then, we inject the wanted field in the `FieldService` so we can know
101
         * later which field we're working with.
102
         */
103
        $this->injectFieldInService($this->arguments['name']);
104
105
        /*
106
         * Activating the slot service, which will be used all along the
107
         * rendering of this very field.
108
         */
109
        $this->slotService->activate($this->renderingContext);
0 ignored issues
show
Compatibility introduced by
$this->renderingContext of type object<TYPO3Fluid\Fluid\...deringContextInterface> is not a sub-type of object<TYPO3\CMS\Fluid\C...deringContextInterface>. It seems like you assume a child interface of the interface TYPO3Fluid\Fluid\Core\Re...nderingContextInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
110
111
        /*
112
         * Calling this here will process every view helper beneath this one,
113
         * allowing options and slots to be used correctly in the field layout.
114
         */
115
        $this->renderChildren();
116
117
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
118
            $restoreCallback = $this->storeViewDataLegacy();
0 ignored issues
show
Deprecated Code introduced by
The method Romm\Formz\ViewHelpers\F...::storeViewDataLegacy() has been deprecated with message: Will be deleted when TYPO3 7.6 is not supported anymore.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
119
        }
120
121
        $templateArguments = $this->getTemplateArguments();
122
123
        $result = $this->renderLayoutView($templateArguments);
124
125
        /*
126
         * Resetting all services data.
127
         */
128
        $this->fieldService->removeCurrentField();
129
        $this->slotService->resetState();
130
131
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
132
            /** @noinspection PhpUndefinedVariableInspection */
133
            $restoreCallback($templateArguments);
0 ignored issues
show
Bug introduced by
The variable $restoreCallback does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
134
        }
135
136
        return $result;
137
    }
138
139
    /**
140
     * Will return the associated Fluid view for this field (configured with the
141
     * `layout` argument).
142
     *
143
     * @param array $templateArguments
144
     * @return string
145
     */
146
    protected function renderLayoutView(array $templateArguments)
147
    {
148
        $fieldName = $this->arguments['name'];
149
        $formObject = $this->formService->getFormObject();
150
        $formConfiguration = $formObject->getConfiguration();
151
        $viewConfiguration = $formConfiguration->getRootConfiguration()->getView();
152
        $layout = $this->getLayout($viewConfiguration);
153
154
        $templateArguments['layout'] = $layout->getLayout();
155
        $templateArguments['formName'] = $formObject->getName();
156
        $templateArguments['fieldName'] = $fieldName;
157
        $templateArguments['fieldId'] = ($templateArguments['fieldId']) ?: StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
158
159
        $view = $this->fieldService->getView($layout);
160
161
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
162
            $view->setRenderingContext($this->renderingContext);
163
        } else {
164
            $renderingContext = $view->getRenderingContext();
165
166
            // Removing all variables previously added to the provider.
167
            $provider = $renderingContext->getVariableProvider();
168
169
            foreach ($provider->getAllIdentifiers() as $key) {
170
                $provider->remove($key);
171
            }
172
173
            /*
174
             * Updating the view dependencies: the variable container as well as
175
             * the controller context must be injected in the view.
176
             */
177
            $renderingContext->setViewHelperVariableContainer($this->viewHelperVariableContainer);
178
179
            $view->setControllerContext($this->controllerContext);
180
181
            $this->viewHelperVariableContainer->setView($view);
182
        }
183
184
        $view->setLayoutRootPaths($this->getPaths('layout'));
0 ignored issues
show
Deprecated Code introduced by
The method Romm\Formz\ViewHelpers\FieldViewHelper::getPaths() has been deprecated with message: Must be removed when TYPO3 7.6 is not supported anymore!

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
185
        $view->setPartialRootPaths($this->getPaths('partial'));
0 ignored issues
show
Deprecated Code introduced by
The method Romm\Formz\ViewHelpers\FieldViewHelper::getPaths() has been deprecated with message: Must be removed when TYPO3 7.6 is not supported anymore!

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
186
        $view->assignMultiple($templateArguments);
187
188
        return $view->render();
189
    }
190
191
    /**
192
     * Temporary solution for TYPO3 6.2 to 7.6 that will store the current view
193
     * variables, to be able to restore them later.
194
     *
195
     * A callback function is returned; it will be called once the field layout
196
     * view was processed, and will restore all the view data.
197
     *
198
     * @return \Closure
199
     *
200
     * @deprecated Will be deleted when TYPO3 7.6 is not supported anymore.
201
     */
202
    protected function storeViewDataLegacy()
203
    {
204
        $originalArguments = [];
205
206
        $variableProvider = $this->getVariableProvider();
207
208
        foreach (self::$reservedVariablesNames as $key) {
209
            if ($variableProvider->exists($key)) {
210
                $originalArguments[$key] = $variableProvider->get($key);
211
            }
212
        }
213
214
        $viewHelperVariableContainer = $this->renderingContext->getViewHelperVariableContainer();
215
        $currentView = $viewHelperVariableContainer->getView();
216
217
        return function (array $templateArguments) use ($originalArguments, $variableProvider, $viewHelperVariableContainer, $currentView) {
218
            $viewHelperVariableContainer->setView($currentView);
219
220
            /*
221
             * Cleaning up the variables in the provider: the original
222
             * values are restored to make the provider like it was before
223
             * the field rendering started.
224
             */
225
            foreach ($variableProvider->getAllIdentifiers() as $identifier) {
226
                if (array_key_exists($identifier, $templateArguments)) {
227
                    $variableProvider->remove($identifier);
228
                }
229
            }
230
231
            foreach ($originalArguments as $key => $value) {
232
                if ($variableProvider->exists($key)) {
233
                    $variableProvider->remove($key);
234
                }
235
236
                $variableProvider->add($key, $value);
237
            }
238
        };
239
    }
240
241
    /**
242
     * Will check that the given field exists in the current form definition and
243
     * inject it in the `FieldService` as `currentField`.
244
     *
245
     * Throws an error if the field is not found or incorrect.
246
     *
247
     * @param string $fieldName
248
     * @throws InvalidArgumentTypeException
249
     * @throws PropertyNotAccessibleException
250
     */
251
    protected function injectFieldInService($fieldName)
252
    {
253
        $formObject = $this->formService->getFormObject();
254
        $formConfiguration = $formObject->getConfiguration();
255
256
        if (false === is_string($fieldName)) {
257
            throw InvalidArgumentTypeException::fieldViewHelperInvalidTypeNameArgument();
258
        } elseif (false === $formConfiguration->hasField($fieldName)) {
259
            throw PropertyNotAccessibleException::fieldViewHelperFieldNotAccessibleInForm($formObject, $fieldName);
260
        }
261
262
        $this->fieldService->setCurrentField($formConfiguration->getField($fieldName));
263
    }
264
265
    /**
266
     * Returns the layout instance used by this field.
267
     *
268
     * @param View $viewConfiguration
269
     * @return Layout
270
     * @throws EntryNotFoundException
271
     * @throws InvalidArgumentTypeException
272
     * @throws InvalidArgumentValueException
273
     */
274
    protected function getLayout(View $viewConfiguration)
275
    {
276
        $layout = $this->arguments['layout'];
277
278
        if (false === is_string($layout)) {
279
            throw InvalidArgumentTypeException::invalidTypeNameArgumentFieldViewHelper($layout);
280
        }
281
282
        list($layoutName, $templateName) = GeneralUtility::trimExplode('.', $layout);
283
284
        if (empty($templateName)) {
285
            $templateName = 'default';
286
        }
287
288
        if (empty($layoutName)) {
289
            throw InvalidArgumentValueException::fieldViewHelperEmptyLayout();
290
        }
291
292
        if (false === $viewConfiguration->hasLayout($layoutName)) {
293
            throw EntryNotFoundException::fieldViewHelperLayoutNotFound($layout);
294
        }
295
296
        if (false === $viewConfiguration->getLayout($layoutName)->hasItem($templateName)) {
297
            throw EntryNotFoundException::fieldViewHelperLayoutItemNotFound($layout, $templateName);
298
        }
299
300
        return $viewConfiguration->getLayout($layoutName)->getItem($templateName);
301
    }
302
303
    /**
304
     * Merging the arguments with the ones registered with the
305
     * `OptionViewHelper`.
306
     *
307
     * @return array
308
     */
309
    protected function getTemplateArguments()
310
    {
311
        $templateArguments = $this->arguments['arguments'] ?: [];
312
        ArrayUtility::mergeRecursiveWithOverrule($templateArguments, $this->fieldService->getFieldOptions());
313
314
        return $templateArguments;
315
    }
316
317
    /**
318
     * This function will determinate the layout/partial root paths that should
319
     * be given to the standalone view. This must be a merge between the paths
320
     * given in the TypoScript configuration and the paths of the current view.
321
     *
322
     * This way, the user can use the layouts/partials from both the form
323
     * rendering extension, as well as the ones used by the field layout.
324
     *
325
     * Please note that TYPO3 v8+ has this behaviour by default, meaning only
326
     * the TypoScript configuration paths are needed, however in TYPO3 v7.6- we
327
     * need to access the root paths, which is *not* granted by Fluid... We are
328
     * then forced to use reflection, please don't do this at home!
329
     *
330
     * @param string $type `partial` or `layout`
331
     * @return array
332
     *
333
     * @deprecated Must be removed when TYPO3 7.6 is not supported anymore!
334
     */
335
    protected function getPaths($type)
336
    {
337
        $viewConfiguration = $this->formService->getFormObject()->getConfiguration()->getRootConfiguration()->getView();
338
339
        $paths = $type === 'partial'
340
            ? $viewConfiguration->getAbsolutePartialRootPaths()
341
            : $viewConfiguration->getAbsoluteLayoutRootPaths();
342
343
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '>=')) {
344
            return $paths;
345
        } else {
346
            $currentView = $this->renderingContext->getViewHelperVariableContainer()->getView();
347
            $propertyName = $type === 'partial'
348
                ? 'getPartialRootPaths'
349
                : 'getLayoutRootPaths';
350
351
            $reflectionClass = new \ReflectionClass($currentView);
352
            $method = $reflectionClass->getMethod($propertyName);
353
            $method->setAccessible(true);
354
355
            $value = $method->invoke($currentView);
356
357
            return array_unique(array_merge($paths, $value));
358
        }
359
    }
360
361
    /**
362
     * @param FormViewHelperService $service
363
     */
364
    public function injectFormService(FormViewHelperService $service)
365
    {
366
        $this->formService = $service;
367
    }
368
369
    /**
370
     * @param FieldViewHelperService $service
371
     */
372
    public function injectFieldService(FieldViewHelperService $service)
373
    {
374
        $this->fieldService = $service;
375
    }
376
377
    /**
378
     * @param SlotViewHelperService $slotService
379
     */
380
    public function injectSlotService(SlotViewHelperService $slotService)
381
    {
382
        $this->slotService = $slotService;
383
    }
384
}
385