Completed
Push — middleware-wip ( 1ffb75...1f2854 )
by Romain
03:26
created

DataAttributesAssetHandler::getFieldSubmissionDoneDataAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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\AssetHandler\Html;
15
16
use Romm\Formz\AssetHandler\AbstractAssetHandler;
17
use Romm\Formz\Error\FormResult;
18
use Romm\Formz\Error\FormzMessageInterface;
19
use Romm\Formz\Service\MessageService;
20
use Romm\Formz\Service\StringService;
21
use TYPO3\CMS\Extbase\Error\Result;
22
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
23
24
/**
25
 * This asset handler generates several data attributes which will be added to
26
 * the form element in the Fluid template. Most of these data attributes are
27
 * directly bound to fields and their properties.
28
 *
29
 * Example of data attributes:
30
 *  - Fields values: when a field changes, its new value will be indicated in
31
 *    the form with the attribute: `fz-value-{field name}="value"`.
32
 *  - Fields validation: when a field is considered as valid (it passed all its
33
 *    validation rules), the form gets the attribute: `fz-valid-{field name}`.
34
 *  - Fields errors: when a field validation fails with an error, the form gets
35
 *    the attribute: `fz-error-{field name}-{name of the error}`.
36
 *  - Fields warnings and notices: same as errors.
37
 */
38
class DataAttributesAssetHandler extends AbstractAssetHandler
39
{
40
    /**
41
     * Handles the data attributes containing the values of the form fields.
42
     *
43
     * Example: `fz-value-color="blue"`
44
     *
45
     * @param FormResult $formResult
46
     * @return array
47
     */
48
    public function getFieldsValuesDataAttributes(FormResult $formResult)
49
    {
50
        $result = [];
51
        $formObject = $this->getFormObject();
52
        $formInstance = $formObject->getForm();
53
54
        foreach ($formObject->getDefinition()->getFields() as $field) {
55
            $fieldName = $field->getName();
56
57
            if (false === $formResult->fieldIsDeactivated($field)) {
58
                $value = ObjectAccess::getProperty($formInstance, $fieldName);
59
                $value = (is_array($value))
60
                    ? implode(' ', $value)
61
                    : $value;
62
63
                if (false === empty($value)) {
64
                    $result[self::getFieldDataValueKey($fieldName)] = $value;
65
                }
66
            }
67
        }
68
69
        return $result;
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public function getFieldSubmissionDoneDataAttribute()
76
    {
77
        return [self::getFieldSubmissionDone() => '1'];
78
    }
79
80
    /**
81
     * Handles the data attributes for the fields which are valid.
82
     *
83
     * Example: `fz-valid-email="1"`
84
     *
85
     * @return array
86
     */
87
    public function getFieldsValidDataAttributes()
88
    {
89
        $result = [];
90
        $formConfiguration = $this->getFormObject()->getDefinition();
91
        $formResult = $this->getFormObject()->getFormResult();
92
93
        foreach ($formConfiguration->getFields() as $field) {
94
            $fieldName = $field->getName();
95
96
            if (false === $formResult->fieldIsDeactivated($field)
97
                && false === $formResult->forProperty($fieldName)->hasErrors()
98
            ) {
99
                $result[self::getFieldDataValidKey($fieldName)] = '1';
100
            }
101
        }
102
103
        return $result;
104
    }
105
106
    /**
107
     * Handles the data attributes for the fields which got errors, warnings and
108
     * notices.
109
     *
110
     * Examples:
111
     * - `fz-error-email="1"`
112
     * - `fz-error-email-rule-default="1"`
113
     *
114
     * @return array
115
     */
116
    public function getFieldsMessagesDataAttributes()
117
    {
118
        $result = [];
119
        $formConfiguration = $this->getFormObject()->getDefinition();
120
        $formResult = $this->getFormObject()->getFormResult();
121
122
        foreach ($formResult->getSubResults() as $fieldName => $fieldResult) {
123
            if (true === $formConfiguration->hasField($fieldName)
124
                && false === $formResult->fieldIsDeactivated($formConfiguration->getField($fieldName))
125
            ) {
126
                $result += $this->getFieldErrorMessages($fieldName, $fieldResult);
127
                $result += $this->getFieldWarningMessages($fieldName, $fieldResult);
128
                $result += $this->getFieldNoticeMessages($fieldName, $fieldResult);
129
            }
130
        }
131
132
        return $result;
133
    }
134
135
    /**
136
     * @param string $fieldName
137
     * @param Result $fieldResult
138
     * @return array
139
     */
140
    protected function getFieldErrorMessages($fieldName, Result $fieldResult)
141
    {
142
        return (true === $fieldResult->hasErrors())
143
            ? $this->addFieldMessageDataAttribute($fieldName, $fieldResult->getErrors(), 'error')
0 ignored issues
show
Documentation introduced by
$fieldResult->getErrors() is of type array<integer,object<TYP...S\Extbase\Error\Error>>, but the function expects a array<integer,object<Rom...FormzMessageInterface>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
            : [];
145
    }
146
147
    /**
148
     * @param string $fieldName
149
     * @param Result $fieldResult
150
     * @return array
151
     */
152
    protected function getFieldWarningMessages($fieldName, Result $fieldResult)
153
    {
154
        return (true === $fieldResult->hasWarnings())
155
            ? $this->addFieldMessageDataAttribute($fieldName, $fieldResult->getWarnings(), 'warning')
0 ignored issues
show
Documentation introduced by
$fieldResult->getWarnings() is of type array<integer,object<TYP...Extbase\Error\Warning>>, but the function expects a array<integer,object<Rom...FormzMessageInterface>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
156
            : [];
157
    }
158
159
    /**
160
     * @param string $fieldName
161
     * @param Result $fieldResult
162
     * @return array
163
     */
164
    protected function getFieldNoticeMessages($fieldName, Result $fieldResult)
165
    {
166
        return (true === $fieldResult->hasNotices())
167
            ? $this->addFieldMessageDataAttribute($fieldName, $fieldResult->getNotices(), 'notice')
0 ignored issues
show
Documentation introduced by
$fieldResult->getNotices() is of type array<integer,object<TYP...\Extbase\Error\Notice>>, but the function expects a array<integer,object<Rom...FormzMessageInterface>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
168
            : [];
169
    }
170
171
    /**
172
     * @param string                  $fieldName
173
     * @param FormzMessageInterface[] $messages
174
     * @param string                  $type
175
     * @return array
176
     */
177
    protected function addFieldMessageDataAttribute($fieldName, array $messages, $type)
178
    {
179
        $result = [self::getFieldDataMessageKey($fieldName, $type) => '1'];
180
181
        foreach ($messages as $message) {
182
            $validationName = MessageService::get()->getMessageValidationName($message);
183
            $messageKey = MessageService::get()->getMessageKey($message);
184
185
            $result[self::getFieldDataValidationMessageKey($fieldName, $type, $validationName, $messageKey)] = '1';
186
        }
187
188
        return $result;
189
    }
190
191
    /**
192
     * Formats the data value attribute key for a given field name.
193
     *
194
     * @param string $fieldName Name of the field.
195
     * @return string
196
     */
197
    public static function getFieldDataValueKey($fieldName)
198
    {
199
        return 'fz-value-' . StringService::get()->sanitizeString($fieldName);
200
    }
201
202
    /**
203
     * Formats the data valid attribute key for a given field name.
204
     *
205
     * @param string $fieldName Name of the field.
206
     * @return string
207
     */
208
    public static function getFieldDataValidKey($fieldName)
209
    {
210
        return 'fz-valid-' . StringService::get()->sanitizeString($fieldName);
211
    }
212
213
    /**
214
     * Formats the data message attribute key for a given field name.
215
     *
216
     * @param string $fieldName Name of the field.
217
     * @param string $type      Type of the message: `error`, `warning` or `notice`.
218
     * @return string
219
     */
220
    public static function getFieldDataMessageKey($fieldName, $type = 'error')
221
    {
222
        return 'fz-' . $type . '-' . StringService::get()->sanitizeString($fieldName);
223
    }
224
225
    /**
226
     * @return string
227
     */
228
    public static function getFieldSubmissionDone()
229
    {
230
        return 'fz-submission-done';
231
    }
232
233
    /**
234
     * Formats the data message attribute key for a given failed validation for
235
     * the given field name.
236
     *
237
     * @param string $fieldName
238
     * @param string $type Type of the message: `error`, `warning` or `notice`.
239
     * @param string $validationName
240
     * @param string $messageKey
241
     * @return string
242
     */
243
    public static function getFieldDataValidationMessageKey($fieldName, $type, $validationName, $messageKey)
244
    {
245
        $stringService = StringService::get();
246
247
        return vsprintf(
248
            'fz-%s-%s-%s-%s',
249
            [
250
                $type,
251
                $stringService->sanitizeString($fieldName),
252
                $stringService->sanitizeString($validationName),
253
                $stringService->sanitizeString($messageKey)
254
            ]
255
        );
256
    }
257
}
258