Completed
Push — unit-test-view-helpers ( 2824c7...96d65b )
by Romain
02:43
created

FormViewHelper::renderViewHelper()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 20
nc 4
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\AssetHandler\AssetHandlerFactory;
17
use Romm\Formz\AssetHandler\Connector\AssetHandlerConnectorManager;
18
use Romm\Formz\AssetHandler\Html\DataAttributesAssetHandler;
19
use Romm\Formz\Behaviours\BehavioursManager;
20
use Romm\Formz\Form\FormInterface;
21
use Romm\Formz\Form\FormObjectFactory;
22
use Romm\Formz\Service\ContextService;
23
use Romm\Formz\Service\ExtensionService;
24
use Romm\Formz\Service\StringService;
25
use Romm\Formz\Service\TimeTrackerService;
26
use Romm\Formz\Validation\Validator\Form\AbstractFormValidator;
27
use Romm\Formz\Validation\Validator\Form\DefaultFormValidator;
28
use Romm\Formz\ViewHelpers\Service\FormService;
29
use TYPO3\CMS\Core\Page\PageRenderer;
30
use TYPO3\CMS\Core\Utility\GeneralUtility;
31
use TYPO3\CMS\Extbase\Error\Result;
32
use TYPO3\CMS\Extbase\Reflection\ReflectionService;
33
use TYPO3\CMS\Fluid\View\StandaloneView;
34
35
/**
36
 * This view helper overrides the default one from Extbase, to include
37
 * everything the extension needs to work properly.
38
 *
39
 * The only difference in Fluid is that the attribute "name" becomes mandatory,
40
 * and must be the exact same name as the form parameter in the controller
41
 * action called when the form is submitted. For instance, if your action looks
42
 * like this: `public function submitAction(ExampleForm $exampleForm) {...}`,
43
 * then the "name" attribute of this view helper must be "exampleForm".
44
 *
45
 * Thanks to the information of the form, the following things are automatically
46
 * handled in this view helper:
47
 *
48
 * - Class
49
 *   A custom class may be added to the form DOM element. If the TypoScript
50
 *   configuration "settings.defaultClass" is set for this form, then the given
51
 *   class will be added to the form element.
52
 *
53
 * - JavaScript
54
 *   A block of JavaScript is built from scratch, which will initialize the
55
 *   form, add validation rules to the fields, and handle activation of the
56
 *   fields validation.
57
 *
58
 * - Data attributes
59
 *   To help integrators customize every aspect they need in CSS, every useful
60
 *   information is put in data attributes in the form DOM element. For example,
61
 *   you can know in real time if the field "email" is valid if the form has the
62
 *   attribute "formz-valid-email"
63
 *
64
 * - CSS
65
 *   A block of CSS is built from scratch, which will handle the fields display,
66
 *   depending on their activation property.
67
 */
68
class FormViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper
69
{
70
    /**
71
     * @var PageRenderer
72
     */
73
    protected $pageRenderer;
74
75
    /**
76
     * @var FormObjectFactory
77
     */
78
    protected $formObjectFactory;
79
80
    /**
81
     * @var FormService
82
     */
83
    protected $formService;
84
85
    /**
86
     * @var string
87
     */
88
    protected $formObjectClassName;
89
90
    /**
91
     * @var AssetHandlerFactory
92
     */
93
    protected $assetHandlerFactory;
94
95
    /**
96
     * @var TimeTrackerService
97
     */
98
    protected $timeTracker;
99
100
    /**
101
     * @inheritdoc
102
     */
103
    public function initialize()
104
    {
105
        parent::initialize();
106
107
        /*
108
         * Important: we need to instantiate the page renderer with this instead
109
         * of Extbase object manager (or with an inject function).
110
         *
111
         * This is due to some TYPO3 low level behaviour which overrides the
112
         * page renderer singleton instance, whenever a new request is used. The
113
         * problem is that the instance is not updated on Extbase side.
114
         *
115
         * Using Extbase injection can lead to old page renderer instance being
116
         * used, resulting in a leak of assets inclusion, and maybe more issues.
117
         */
118
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
119
    }
120
121
    /**
122
     * @inheritdoc
123
     */
124
    public function initializeArguments()
125
    {
126
        parent::initializeArguments();
127
128
        // The name attribute becomes mandatory.
129
        $this->overrideArgument('name', 'string', 'Name of the form', true);
130
        $this->registerArgument('formClassName', 'string', 'Class name of the form.', false);
131
    }
132
133
    /**
134
     * @return string
135
     */
136
    public function renderViewHelper()
137
    {
138
        $this->timeTracker = TimeTrackerService::getAndStart();
139
        $result = '';
140
141
        if (false === ContextService::get()->isTypoScriptIncluded()) {
142
            if (ExtensionService::get()->isInDebugMode()) {
143
                $result = ContextService::get()->translate('form.typoscript_not_included.error_message');
144
            }
145
        } else {
146
            $formObject = $this->formObjectFactory->getInstanceFromClassName($this->getFormObjectClassName(), $this->getFormObjectName());
147
148
            $this->formService->setFormObject($formObject);
149
            $formzValidationResult = $formObject->getConfigurationValidationResult();
150
151
            if ($formzValidationResult->hasErrors()) {
152
                // If the form configuration is not valid, we display the errors list.
153
                $result = $this->getErrorText($formzValidationResult);
154
            } else {
155
                // Everything is ok, we render the form.
156
                $result = $this->renderForm(func_get_args());
157
            }
158
159
            unset($formzValidationResult);
160
        }
161
162
        $this->timeTracker->logTime('final');
163
        $result = $this->timeTracker->getHTMLCommentLogs() . LF . $result;
164
        unset($this->timeTracker);
165
166
        $this->formService->resetState();
167
168
        return $result;
169
    }
170
    /**
171
     * Will render the whole form and return the HTML result.
172
     *
173
     * @param array $arguments
174
     * @return string
175
     */
176
    final protected function renderForm(array $arguments)
177
    {
178
        $this->timeTracker->logTime('post-config');
179
180
        $this->assetHandlerFactory = AssetHandlerFactory::get($this->formService->getFormObject(), $this->controllerContext);
181
182
        $this->setObjectAndRequestResult()
183
            ->applyBehavioursOnSubmittedForm()
184
            ->addDefaultClass()
185
            ->handleDataAttributes();
186
187
        $assetHandlerConnectorManager = AssetHandlerConnectorManager::get($this->pageRenderer, $this->assetHandlerFactory);
188
        $assetHandlerConnectorManager->includeDefaultAssets();
189
        $assetHandlerConnectorManager->getJavaScriptAssetHandlerConnector()
190
            ->generateAndIncludeFormzConfigurationJavaScript()
191
            ->generateAndIncludeJavaScript()
192
            ->generateAndIncludeInlineJavaScript()
193
            ->includeJavaScriptValidationAndConditionFiles();
194
        $assetHandlerConnectorManager->getCssAssetHandlerConnector()->includeGeneratedCss();
195
196
        $this->timeTracker->logTime('pre-render');
197
198
        // Renders the whole Fluid template.
199
        $result = call_user_func_array([get_parent_class(), 'render'], $arguments);
200
201
        $assetHandlerConnectorManager->getJavaScriptAssetHandlerConnector()->includeLanguageJavaScriptFiles();
202
203
        return $result;
204
    }
205
206
    /**
207
     * This function will inject in the variable container the instance of form
208
     * and its submission result. There are only two ways to be sure the values
209
     * injected are correct: when the form has actually been submitted by the
210
     * user, or when the view helper argument `object` is filled.
211
     *
212
     * @return $this
213
     */
214
    protected function setObjectAndRequestResult()
215
    {
216
        $this->formService->activateFormContext();
217
218
        $originalRequest = $this->controllerContext
219
            ->getRequest()
220
            ->getOriginalRequest();
221
222
        if (null !== $originalRequest
223
            && $originalRequest->hasArgument($this->getFormObjectName())
224
        ) {
225
            /** @var array $formInstance */
226
            $formInstance = $originalRequest->getArgument($this->getFormObjectName());
227
228
            $formRequestResult = AbstractFormValidator::getFormValidationResult(
229
                $this->getFormObjectClassName(),
230
                $this->getFormObjectName()
231
            );
232
233
            $this->formService->setFormInstance($formInstance);
234
            $this->formService->setFormResult($formRequestResult);
235
            $this->formService->markFormAsSubmitted();
236
        } elseif (null !== $this->arguments['object']) {
237
            $formInstance = $this->arguments['object'];
238
239
            /*
240
             * @todo: pas forcément un DefaultFormValidator: comment je gère ça?
241
             * + ça prend quand même un peu de temps cette manière. Peut-on faire autrement ?
242
             */
243
            /** @var DefaultFormValidator $formValidator */
244
            $formValidator = GeneralUtility::makeInstance(
245
                DefaultFormValidator::class,
246
                ['name' => $this->getFormObjectName()]
247
            );
248
            $formRequestResult = $formValidator->validate($formInstance);
249
250
            $this->formService->setFormInstance($formInstance);
251
            $this->formService->setFormResult($formRequestResult);
252
        }
253
254
        return $this;
255
    }
256
257
    /**
258
     * Will loop on the submitted form fields and apply behaviours if their
259
     * configuration contains.
260
     *
261
     * @return $this
262
     */
263
    protected function applyBehavioursOnSubmittedForm()
264
    {
265
        $originalRequest = $this->controllerContext
266
            ->getRequest()
267
            ->getOriginalRequest();
268
269
        if ($this->formService->formWasSubmitted()) {
270
            /** @var BehavioursManager $behavioursManager */
271
            $behavioursManager = GeneralUtility::makeInstance(BehavioursManager::class);
272
273
            $formProperties = $behavioursManager->applyBehaviourOnPropertiesArray(
274
                $this->formService->getFormInstance(),
275
                $this->formService->getFormObject()->getConfiguration()
276
            );
277
278
            $originalRequest->setArgument($this->getFormObjectName(), $formProperties);
279
        }
280
281
        return $this;
282
    }
283
284
    /**
285
     * Will add a default class to the form element.
286
     *
287
     * To customize the class, take a look at `settings.defaultClass` in the
288
     * form TypoScript configuration.
289
     *
290
     * @return $this
291
     */
292
    protected function addDefaultClass()
293
    {
294
        $formDefaultClass = $this->formService
295
            ->getFormObject()
296
            ->getConfiguration()
297
            ->getSettings()
298
            ->getDefaultClass();
299
300
        $class = $this->tag->getAttribute('class');
301
302
        if (false === empty($formDefaultClass)) {
303
            $class = ((!empty($class)) ? $class . ' ' : '') . $formDefaultClass;
304
        }
305
306
        $this->tag->addAttribute('class', $class);
307
308
        return $this;
309
    }
310
311
    /**
312
     * Adds custom data attributes to the form element, based on the
313
     * submitted form values and results.
314
     *
315
     * @return $this
316
     */
317
    protected function handleDataAttributes()
318
    {
319
        $object = $this->formService->getFormInstance();
320
        $formResult = $this->formService->getFormResult();
321
322
        /** @var DataAttributesAssetHandler $dataAttributesAssetHandler */
323
        $dataAttributesAssetHandler =  $this->assetHandlerFactory->getAssetHandler(DataAttributesAssetHandler::class);
324
325
        $dataAttributes = [];
326
        if ($object) {
327
            $dataAttributes += $dataAttributesAssetHandler->getFieldsValuesDataAttributes($object, $formResult);
328
        }
329
330
        if ($formResult) {
331
            $dataAttributes += $dataAttributesAssetHandler->getFieldsValidDataAttributes($formResult);
332
333
            if (true === $this->formService->formWasSubmitted()) {
334
                $dataAttributes += ['formz-submission-done' => '1'];
335
                $dataAttributes += $dataAttributesAssetHandler->getFieldsErrorsDataAttributes($formResult);
336
            }
337
        }
338
339
        foreach ($dataAttributes as $attributeName => $attributeValue) {
340
            $this->tag->addAttribute($attributeName, $attributeValue);
341
        }
342
343
        return $this;
344
    }
345
346
    /**
347
     * Will return an error text from a Fluid view.
348
     *
349
     * @param Result $result
350
     * @return string
351
     */
352
    protected function getErrorText(Result $result)
353
    {
354
        /** @var $view \TYPO3\CMS\Fluid\View\StandaloneView */
355
        $view = $this->objectManager->get(StandaloneView::class);
356
        $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:' . ExtensionService::get()->getExtensionKey() . '/Resources/Private/Templates/Error/ConfigurationErrorBlock.html'));
357
        $layoutRootPath = StringService::get()->getExtensionRelativePath('Resources/Private/Layouts');
358
        $view->setLayoutRootPaths([$layoutRootPath]);
359
        $view->assign('result', $result);
360
361
        $templatePath = GeneralUtility::getFileAbsFileName('EXT:' . ExtensionService::get()->getExtensionKey() . '/Resources/Public/StyleSheets/Form.ErrorBlock.css');
362
        $this->pageRenderer->addCssFile(StringService::get()->getResourceRelativePath($templatePath));
363
364
        return $view->render();
365
    }
366
367
    /**
368
     * Returns the class name of the form object: it is fetched from the action
369
     * of the controller which will be called when submitting this form. It
370
     * means two things:
371
     * - The action must have a parameter which has the exact same name as the
372
     *   form.
373
     * - The parameter must indicate its type.
374
     *
375
     * @return null|string
376
     * @throws \Exception
377
     */
378
    protected function getFormObjectClassName()
379
    {
380
        if (null === $this->formObjectClassName) {
381
            $request = $this->controllerContext->getRequest();
382
            $controllerObjectName = $request->getControllerObjectName();
383
            $actionName = ($this->arguments['action']) ?: $request->getControllerActionName();
384
            $actionName = $actionName . 'Action';
385
386
            if ($this->hasArgument('formClassName')) {
387
                $formClassName = $this->arguments['formClassName'];
388
            } else {
389
                /** @var ReflectionService $reflectionService */
390
                $reflectionService = $this->objectManager->get(ReflectionService::class);
391
                $methodParameters = $reflectionService->getMethodParameters($controllerObjectName, $actionName);
392
393
                if (false === isset($methodParameters[$this->getFormObjectName()])) {
394
                    throw new \Exception(
395
                        'The method "' . $controllerObjectName . '::' . $actionName . '()" must have a parameter "$' . $this->getFormObjectName() . '". Note that you can also change the parameter "name" of the form view helper.',
396
                        1457441846
397
                    );
398
                }
399
400
                $formClassName = $methodParameters[$this->getFormObjectName()]['type'];
401
            }
402
403
            if (false === class_exists($formClassName)) {
404
                throw new \Exception(
405
                    'Invalid value for the form class name (current value: "' . $formClassName . '"). You need to either fill the parameter "formClassName" in the view helper, or specify the type of the parameter "$' . $this->getFormObjectName() . '" for the method "' . $controllerObjectName . '::' . $actionName . '()".',
406
                    1457442014
407
                );
408
            }
409
410
            if (false === in_array(FormInterface::class, class_implements($formClassName))) {
411
                throw new \Exception(
412
                    'Invalid value for the form class name (current value: "' . $formClassName . '"); it must be an instance of "' . FormInterface::class . '".',
413
                    1457442462
414
                );
415
            }
416
417
            $this->formObjectClassName = $formClassName;
418
        }
419
420
        return $this->formObjectClassName;
421
    }
422
423
    /**
424
     * @param PageRenderer $pageRenderer
425
     */
426
    public function injectPageRenderer(PageRenderer $pageRenderer)
427
    {
428
        $this->pageRenderer = $pageRenderer;
429
    }
430
431
    /**
432
     * @param FormObjectFactory $formObjectFactory
433
     */
434
    public function injectFormObjectFactory(FormObjectFactory $formObjectFactory)
435
    {
436
        $this->formObjectFactory = $formObjectFactory;
437
    }
438
439
    /**
440
     * @param FormService $service
441
     */
442
    public function injectFormService(FormService $service)
443
    {
444
        $this->formService = $service;
445
    }
446
}
447