Completed
Branch unit-test-view-helpers (ccaf92)
by Romain
01:50
created

FormViewHelper::setObjectAndRequestResult()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 42
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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