Completed
Push — bugfix/field-layout-v8 ( cc1cfe )
by Romain
03:29
created

FieldViewHelper::storeViewDataLegacy()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 38
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 17
nc 3
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
     * @inheritdoc
73
     */
74
    public function initializeArguments()
75
    {
76
        $this->registerArgument('name', 'string', 'Name of the field which should be rendered.', true);
77
        $this->registerArgument('layout', 'string', 'Path of the TypoScript layout which will be used.', true);
78
        $this->registerArgument('arguments', 'array', 'Arbitrary arguments which will be sent to the field template.', false, []);
79
    }
80
81
    /**
82
     * @inheritdoc
83
     */
84
    public function render()
85
    {
86
        /*
87
         * First, we check if this view helper is called from within the
88
         * `FormViewHelper`, because it would not make sense anywhere else.
89
         */
90
        if (false === $this->formService->formContextExists()) {
91
            throw ContextNotFoundException::fieldViewHelperFormContextNotFound();
92
        }
93
94
        /*
95
         * Then, we inject the wanted field in the `FieldService` so we can know
96
         * later which field we're working with.
97
         */
98
        $this->injectFieldInService($this->arguments['name']);
99
100
        /*
101
         * Activating the slot service, which will be used all along the
102
         * rendering of this very field.
103
         */
104
        $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...
105
106
        /*
107
         * Calling this here will process every view helper beneath this one,
108
         * allowing options and slots to be used correctly in the field layout.
109
         */
110
        $this->renderChildren();
111
112
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
113
            $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...
114
        }
115
116
        $templateArguments = $this->getTemplateArguments();
117
118
        $result = $this->renderLayoutView($templateArguments);
119
120
        /*
121
         * Resetting all services data.
122
         */
123
        $this->fieldService->removeCurrentField();
124
        $this->slotService->resetState();
125
126
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
127
            /** @noinspection PhpUndefinedVariableInspection */
128
            $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...
129
        }
130
131
        return $result;
132
    }
133
134
    /**
135
     * Will return the associated Fluid view for this field (configured with the
136
     * `layout` argument).
137
     *
138
     * @param array $templateArguments
139
     * @return string
140
     */
141
    protected function renderLayoutView(array $templateArguments)
142
    {
143
        $fieldName = $this->arguments['name'];
144
        $formObject = $this->formService->getFormObject();
145
        $formConfiguration = $formObject->getConfiguration();
146
        $viewConfiguration = $formConfiguration->getRootConfiguration()->getView();
147
        $layout = $this->getLayout($viewConfiguration);
148
149
        $templateArguments['layout'] = $layout->getLayout();
150
        $templateArguments['formName'] = $formObject->getName();
151
        $templateArguments['fieldName'] = $fieldName;
152
        $templateArguments['fieldId'] = ($templateArguments['fieldId']) ?: StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
153
154
        $view = $this->fieldService->getView($layout);
155
156
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '<')) {
157
            $view->setRenderingContext($this->renderingContext);
158
        } else {
159
            $renderingContext = $view->getRenderingContext();
160
161
            // Removing all variables previously added to the provider.
162
            $provider = $renderingContext->getVariableProvider();
163
164
            foreach ($provider->getAllIdentifiers() as $key) {
165
                $provider->remove($key);
166
            }
167
168
            /*
169
             * Updating the view dependencies: the variable container as well as
170
             * the controller context must be injected in the view.
171
             */
172
            $renderingContext->setViewHelperVariableContainer($this->viewHelperVariableContainer);
173
174
            $view->setControllerContext($this->controllerContext);
175
176
            $this->viewHelperVariableContainer->setView($view);
177
        }
178
179
        $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...
180
        $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...
181
        $view->assignMultiple($templateArguments);
182
183
        return $view->render();
184
    }
185
186
    /**
187
     * Temporary solution for TYPO3 6.2 to 7.6 that will store the current view
188
     * variables, to be able to restore them later.
189
     *
190
     * A callback function is returned; it will be called once the field layout
191
     * view was processed, and will restore all the view data.
192
     *
193
     * @return \Closure
194
     *
195
     * @deprecated Will be deleted when TYPO3 7.6 is not supported anymore.
196
     */
197
    protected function storeViewDataLegacy()
198
    {
199
        $originalArguments = [];
200
201
        $variableProvider = $this->getVariableProvider();
202
203
        foreach (self::$reservedVariablesNames as $key) {
204
            if ($variableProvider->exists($key)) {
205
                $originalArguments[$key] = $variableProvider->get($key);
206
            }
207
        }
208
209
        $viewHelperVariableContainer = $this->renderingContext->getViewHelperVariableContainer();
210
        $currentView = $viewHelperVariableContainer->getView();
211
212
        return function (array $templateArguments) use ($originalArguments, $variableProvider, $viewHelperVariableContainer, $currentView) {
213
            $viewHelperVariableContainer->setView($currentView);
214
215
            /*
216
             * Cleaning up the variables in the provider: the original
217
             * values are restored to make the provider like it was before
218
             * the field rendering started.
219
             */
220
            foreach ($variableProvider->getAllIdentifiers() as $identifier) {
221
                if (array_key_exists($identifier, $templateArguments)) {
222
                    $variableProvider->remove($identifier);
223
                }
224
            }
225
226
            foreach ($originalArguments as $key => $value) {
227
                if ($variableProvider->exists($key)) {
228
                    $variableProvider->remove($key);
229
                }
230
231
                $variableProvider->add($key, $value);
232
            }
233
        };
234
    }
235
236
    /**
237
     * Will check that the given field exists in the current form definition and
238
     * inject it in the `FieldService` as `currentField`.
239
     *
240
     * Throws an error if the field is not found or incorrect.
241
     *
242
     * @param string $fieldName
243
     * @throws InvalidArgumentTypeException
244
     * @throws PropertyNotAccessibleException
245
     */
246
    protected function injectFieldInService($fieldName)
247
    {
248
        $formObject = $this->formService->getFormObject();
249
        $formConfiguration = $formObject->getConfiguration();
250
251
        if (false === is_string($fieldName)) {
252
            throw InvalidArgumentTypeException::fieldViewHelperInvalidTypeNameArgument();
253
        } elseif (false === $formConfiguration->hasField($fieldName)) {
254
            throw PropertyNotAccessibleException::fieldViewHelperFieldNotAccessibleInForm($formObject, $fieldName);
255
        }
256
257
        $this->fieldService->setCurrentField($formConfiguration->getField($fieldName));
258
    }
259
260
    /**
261
     * Returns the layout instance used by this field.
262
     *
263
     * @param View $viewConfiguration
264
     * @return Layout
265
     * @throws EntryNotFoundException
266
     * @throws InvalidArgumentTypeException
267
     * @throws InvalidArgumentValueException
268
     */
269
    protected function getLayout(View $viewConfiguration)
270
    {
271
        $layout = $this->arguments['layout'];
272
273
        if (false === is_string($layout)) {
274
            throw InvalidArgumentTypeException::invalidTypeNameArgumentFieldViewHelper($layout);
275
        }
276
277
        list($layoutName, $templateName) = GeneralUtility::trimExplode('.', $layout);
278
279
        if (empty($templateName)) {
280
            $templateName = 'default';
281
        }
282
283
        if (empty($layoutName)) {
284
            throw InvalidArgumentValueException::fieldViewHelperEmptyLayout();
285
        }
286
287
        if (false === $viewConfiguration->hasLayout($layoutName)) {
288
            throw EntryNotFoundException::fieldViewHelperLayoutNotFound($layout);
289
        }
290
291
        if (false === $viewConfiguration->getLayout($layoutName)->hasItem($templateName)) {
292
            throw EntryNotFoundException::fieldViewHelperLayoutItemNotFound($layout, $templateName);
293
        }
294
295
        return $viewConfiguration->getLayout($layoutName)->getItem($templateName);
296
    }
297
298
    /**
299
     * Merging the arguments with the ones registered with the
300
     * `OptionViewHelper`.
301
     *
302
     * @return array
303
     */
304
    protected function getTemplateArguments()
305
    {
306
        $templateArguments = $this->arguments['arguments'] ?: [];
307
        ArrayUtility::mergeRecursiveWithOverrule($templateArguments, $this->fieldService->getFieldOptions());
308
309
        return $templateArguments;
310
    }
311
312
    /**
313
     * This function will determinate the layout/partial root paths that should
314
     * be given to the standalone view. This must be a merge between the paths
315
     * given in the TypoScript configuration and the paths of the current view.
316
     *
317
     * This way, the user can use the layouts/partials from both the form
318
     * rendering extension, as well as the ones used by the field layout.
319
     *
320
     * Please note that TYPO3 v8+ has this behaviour by default, meaning only
321
     * the TypoScript configuration paths are needed, however in TYPO3 v7.6- we
322
     * need to access the root paths, which is *not* granted by Fluid... We are
323
     * then forced to use reflection, please don't do this at home!
324
     *
325
     * @param string $type `partial` or `layout`
326
     * @return array
327
     *
328
     * @deprecated Must be removed when TYPO3 7.6 is not supported anymore!
329
     */
330
    protected function getPaths($type)
331
    {
332
        $viewConfiguration = $this->formService->getFormObject()->getConfiguration()->getRootConfiguration()->getView();
333
334
        $paths = $type === 'partial'
335
            ? $viewConfiguration->getAbsolutePartialRootPaths()
336
            : $viewConfiguration->getAbsoluteLayoutRootPaths();
337
338
        if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '8.0.0', '>=')) {
339
            return $paths;
340
        } else {
341
            $currentView = $this->renderingContext->getViewHelperVariableContainer()->getView();
342
            $propertyName = $type === 'partial'
343
                ? 'getPartialRootPaths'
344
                : 'getLayoutRootPaths';
345
346
            $reflectionClass = new \ReflectionClass($currentView);
347
            $method = $reflectionClass->getMethod($propertyName);
348
            $method->setAccessible(true);
349
350
            $value = $method->invoke($currentView);
351
352
            return array_unique(array_merge($paths, $value));
353
        }
354
    }
355
356
    /**
357
     * @param FormViewHelperService $service
358
     */
359
    public function injectFormService(FormViewHelperService $service)
360
    {
361
        $this->formService = $service;
362
    }
363
364
    /**
365
     * @param FieldViewHelperService $service
366
     */
367
    public function injectFieldService(FieldViewHelperService $service)
368
    {
369
        $this->fieldService = $service;
370
    }
371
372
    /**
373
     * @param SlotViewHelperService $slotService
374
     */
375
    public function injectSlotService(SlotViewHelperService $slotService)
376
    {
377
        $this->slotService = $slotService;
378
    }
379
}
380