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

ClassViewHelper::getFormResultClass()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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