Completed
Push — unit-tests-conditions ( a23049...dc9eee )
by Romain
02:30
created

ClassViewHelper::getPropertyResultClass()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 15
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 10
nc 3
nop 1
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\Classes\ViewClass;
17
use Romm\Formz\Exceptions\EntryNotFoundException;
18
use Romm\Formz\Exceptions\InvalidEntryException;
19
use Romm\Formz\Exceptions\UnregisteredConfigurationException;
20
use Romm\Formz\Service\ViewHelper\FieldViewHelperService;
21
use Romm\Formz\Service\ViewHelper\FormViewHelperService;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Extbase\Error\Result;
24
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
25
26
/**
27
 * This view helper is used to manage the properties set in TypoScript at the
28
 * path `config.tx_formz.view.classes`.
29
 *
30
 * Two groups of classes are handled: `errors` and `valid`. The classes will be
31
 * "activated" only when the field has been validated, and the result matches
32
 * the class group.
33
 *
34
 * In the option `name`, you must indicate which class from which group you want
35
 * to manage, for example `errors.has-error` for the class `has-error` from the
36
 * group `errors`.
37
 *
38
 * If the field currently being rendered with Fluid is not using the view helper
39
 * `FieldViewHelper` (all its skeleton is written manually), you may have to use
40
 * the option `field`, which should then contain the name of the field.
41
 *
42
 * Please be aware that this view helper is useful only when used at the same
43
 * level or under the HTML element containing the field selector (usually the
44
 * one with the data attribute `formz-field-container`). You may encounter
45
 * strange behaviours if you do not respect this requirement.
46
 */
47
class ClassViewHelper extends AbstractViewHelper
48
{
49
    const CLASS_ERRORS = 'errors';
50
    const CLASS_VALID = 'valid';
51
52
    /**
53
     * @var array
54
     */
55
    protected static $acceptedClassesNameSpace = [self::CLASS_ERRORS, self::CLASS_VALID];
56
57
    /**
58
     * @var FormViewHelperService
59
     */
60
    protected $formService;
61
62
    /**
63
     * @var FieldViewHelperService
64
     */
65
    protected $fieldService;
66
67
    /**
68
     * @var string
69
     */
70
    protected $fieldName;
71
72
    /**
73
     * @var string
74
     */
75
    protected $classValue;
76
77
    /**
78
     * @var string
79
     */
80
    protected $classNameSpace;
81
82
    /**
83
     * @var string
84
     */
85
    protected $className;
86
87
    /**
88
     * @inheritdoc
89
     */
90
    public function initializeArguments()
91
    {
92
        $this->registerArgument('name', 'string', 'Name of the class which will be managed.', true);
93
        $this->registerArgument('field', 'string', 'Name of the field which will be managed. By default, it is the field from the current `FieldViewHelper`.');
94
    }
95
96
    /**
97
     * @inheritdoc
98
     */
99
    public function render()
100
    {
101
        $this->initializeClassNames();
102
        $this->initializeClassValue();
103
        $this->initializeFieldName();
104
105
        $result = vsprintf(
106
            'formz-%s-%s',
107
            [
108
                $this->classNameSpace,
109
                str_replace(' ', '-', $this->classValue)
110
            ]
111
        );
112
113
        $result .= $this->getFormResultClass();
114
115
        return $result;
116
    }
117
118
    /**
119
     * Will initialize the namespace and name of the class which is given as
120
     * argument to this ViewHelper.
121
     *
122
     * @throws InvalidEntryException
123
     */
124
    protected function initializeClassNames()
125
    {
126
        list($this->classNameSpace, $this->className) = GeneralUtility::trimExplode('.', $this->arguments['name']);
127
128
        if (false === in_array($this->classNameSpace, self::$acceptedClassesNameSpace)) {
129
            throw new InvalidEntryException(
130
                'The class "' . $this->arguments['name'] . '" is not valid: the namespace of the error must be one of the following: ' . implode(', ', self::$acceptedClassesNameSpace) . '.',
131
                1467623504
132
            );
133
        }
134
    }
135
136
    /**
137
     * Fetches the name of the field which should refer to this class. It can
138
     * either be a given value, or be empty if the ViewHelper is used inside a
139
     * `FieldViewHelper`.
140
     *
141
     * @throws EntryNotFoundException
142
     */
143
    protected function initializeFieldName()
144
    {
145
        $this->fieldName = $this->arguments['field'];
146
147
        if (empty($this->fieldName)
148
            && $this->fieldService->fieldContextExists()
149
        ) {
150
            $this->fieldName = $this->fieldService
151
                ->getCurrentField()
152
                ->getFieldName();
153
        }
154
155
        if (null === $this->fieldName) {
156
            throw new EntryNotFoundException(
157
                'The field could not be fetched for the class "' . $this->arguments['name'] . '": please either use this view helper inside the view helper "' . FieldViewHelper::class . '", or fill the parameter "field" of this view helper with the field name you want.',
158
                1467623761
159
            );
160
        }
161
    }
162
163
    /**
164
     * Fetches the corresponding value of this class, which was defined in
165
     * TypoScript.
166
     *
167
     * @throws UnregisteredConfigurationException
168
     */
169
    protected function initializeClassValue()
170
    {
171
        $classesConfiguration = $this->formService
172
            ->getFormObject()
173
            ->getConfiguration()
174
            ->getFormzConfiguration()
175
            ->getView()
176
            ->getClasses();
177
178
        /** @var ViewClass $class */
179
        $class = ObjectAccess::getProperty($classesConfiguration, $this->classNameSpace);
180
181
        if (false === $class->hasItem($this->className)) {
182
            throw new UnregisteredConfigurationException(
183
                'The class "' . $this->arguments['name'] . '" is not valid: the class name "' . $this->className . '" was not found in the namespace "' . $this->classNameSpace . '".',
184
                1467623662
185
            );
186
        }
187
188
        $this->classValue = $class->getItem($this->className);
0 ignored issues
show
Documentation Bug introduced by
It seems like $class->getItem($this->className) can also be of type array. However, the property $classValue is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
189
    }
190
191
    /**
192
     * Checks if the form was submitted, then parses its result to handle
193
     * classes depending on TypoScript configuration.
194
     *
195
     * @return string
196
     */
197
    protected function getFormResultClass()
198
    {
199
        $formResult = $this->formService->getFormResult();
200
        $propertyResult = ($formResult)
201
            ? $formResult->forProperty($this->fieldName)
202
            : null;
203
204
        return ($this->formService->formWasSubmitted() && null !== $propertyResult)
205
            ? $this->getPropertyResultClass($propertyResult)
206
            : '';
207
    }
208
209
    /**
210
     * @param Result $propertyResult
211
     * @return string
212
     */
213
    protected function getPropertyResultClass(Result $propertyResult)
214
    {
215
        $result = '';
216
217
        switch ($this->classNameSpace) {
218
            case self::CLASS_ERRORS:
219
                $result = $this->getPropertyErrorClass($propertyResult);
220
                break;
221
            case self::CLASS_VALID:
222
                $result = $this->getPropertyValidClass($propertyResult);
223
                break;
224
        }
225
226
        return $result;
227
    }
228
229
    /**
230
     * @param Result $propertyResult
231
     * @return string
232
     */
233
    protected function getPropertyErrorClass(Result $propertyResult)
234
    {
235
        return (true === $propertyResult->hasErrors())
236
            ? ' ' . $this->classValue
237
            : '';
238
    }
239
240
    /**
241
     * @param Result $propertyResult
242
     * @return string
243
     */
244
    protected function getPropertyValidClass(Result $propertyResult)
245
    {
246
        $result = '';
247
        $formObject = $this->formService->getFormObject();
248
        $field = $formObject->getConfiguration()->getField($this->fieldName);
249
250
        if (false === $propertyResult->hasErrors()
251
            && false === $formObject->hasLastValidationResult()
252
            || (
253
                $formObject->hasLastValidationResult()
254
                && false === $formObject->getLastValidationResult()->fieldIsDeactivated($field)
0 ignored issues
show
Bug introduced by
It seems like $field defined by $formObject->getConfigur...Field($this->fieldName) on line 248 can be null; however, Romm\Formz\Error\FormResult::fieldIsDeactivated() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
255
            )
256
        ) {
257
            $result .= ' ' . $this->classValue;
258
        }
259
260
        return $result;
261
    }
262
263
    /**
264
     * @param FormViewHelperService $service
265
     */
266
    public function injectFormService(FormViewHelperService $service)
267
    {
268
        $this->formService = $service;
269
    }
270
271
    /**
272
     * @param FieldViewHelperService $service
273
     */
274
    public function injectFieldService(FieldViewHelperService $service)
275
    {
276
        $this->fieldService = $service;
277
    }
278
}
279