Completed
Push — development ( 3395f4...3a475c )
by Romain
10s
created

FormatMessageViewHelper::getFieldName()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 20
rs 9.2
cc 4
eloc 11
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\Configuration\Form\Field\Field;
17
use Romm\Formz\Error\FormzMessageInterface;
18
use Romm\Formz\Exceptions\EntryNotFoundException;
19
use Romm\Formz\Exceptions\InvalidArgumentTypeException;
20
use Romm\Formz\Exceptions\InvalidEntryException;
21
use Romm\Formz\Service\MessageService;
22
use Romm\Formz\Service\StringService;
23
use Romm\Formz\ViewHelpers\Service\FieldService;
24
use Romm\Formz\ViewHelpers\Service\FormService;
25
use TYPO3\CMS\Extbase\Error\Error;
26
use TYPO3\CMS\Extbase\Error\Message;
27
use TYPO3\CMS\Extbase\Error\Notice;
28
use TYPO3\CMS\Extbase\Error\Warning;
29
30
/**
31
 * This view helper can format the validation result messages of a field.
32
 *
33
 * It will use the message template defined for the given field, and handle
34
 * every dynamic value which can be found in the template (see below):
35
 *
36
 * #FIELD# : Name of the field;
37
 * #FIELD_ID# : Value of the `id` attribute of the field DOM element;
38
 * #VALIDATOR# : Name of the validation rule;
39
 * #TYPE#' : Type of the message (usually `error`);
40
 * #KEY#' : Key of the message (usually `default`);
41
 * #MESSAGE# : The message itself.
42
 */
43
class FormatMessageViewHelper extends AbstractViewHelper
44
{
45
    /**
46
     * @var bool
47
     */
48
    protected $escapeOutput = false;
49
50
    /**
51
     * @var FormService
52
     */
53
    protected $formService;
54
55
    /**
56
     * @var FieldService
57
     */
58
    protected $fieldService;
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function initializeArguments()
64
    {
65
        $this->registerArgument('message', 'object', 'The message which will be formatted.', true);
66
        $this->registerArgument('field', 'string', 'Name of the field which will be managed. By default, it is the field from the current `FieldViewHelper`.');
67
    }
68
69
    /**
70
     * @inheritdoc
71
     */
72
    public function render()
73
    {
74
        $message = $this->getMessage();
75
        $fieldName = $this->getFieldName();
76
        $field = $this->getField();
77
        $formObject = $this->formService->getFormObject();
78
79
        $variableProvider = $this->getVariableProvider();
80
81
        $fieldId = ($variableProvider->exists('fieldId'))
82
            ? $variableProvider->get('fieldId')
83
            : StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
84
85
        $result = str_replace(
86
            [
87
                '#FIELD#',
88
                '#FIELD_ID#',
89
                '#TYPE#',
90
                '#VALIDATOR#',
91
                '#KEY#',
92
                '#MESSAGE#'
93
            ],
94
            [
95
                $fieldName,
96
                $fieldId,
97
                $this->getMessageType($message),
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->getMessage() on line 74 can also be of type object<Romm\Formz\Error\FormzMessageInterface>; however, Romm\Formz\ViewHelpers\F...elper::getMessageType() does only seem to accept object<TYPO3\CMS\Extbase\Error\Message>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
98
                MessageService::get()->getMessageValidationName($message),
99
                MessageService::get()->getMessageKey($message),
100
                $message->getMessage()
0 ignored issues
show
Bug introduced by
The method getMessage does only exist in TYPO3\CMS\Extbase\Error\Message, but not in Romm\Formz\Error\FormzMessageInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
101
            ],
102
            $field->getSettings()->getMessageTemplate()
103
        );
104
105
        return $result;
106
    }
107
108
    /**
109
     * @return Message|FormzMessageInterface
110
     * @throws \Exception
111
     */
112
    protected function getMessage()
113
    {
114
        $message = $this->arguments['message'];
115
116
        if (false === $message instanceof Message) {
117
            throw new InvalidArgumentTypeException(
118
                'The argument "message" for the view helper "' . __CLASS__ . '" must be an instance of "' . Message::class . '".',
119
                1467021406
120
            );
121
        }
122
123
        return $message;
124
    }
125
126
    /**
127
     * @param Message $message
128
     * @return string
129
     */
130
    protected function getMessageType(Message $message)
131
    {
132
        if ($message instanceof Error) {
133
            $messageType = 'error';
134
        } elseif ($message instanceof Warning) {
135
            $messageType = 'warning';
136
        } elseif ($message instanceof Notice) {
137
            $messageType = 'notice';
138
        } else {
139
            $messageType = 'message';
140
        }
141
142
        return $messageType;
143
    }
144
145
    /**
146
     * @return string
147
     * @throws \Exception
148
     */
149
    protected function getFieldName()
150
    {
151
        $fieldName = $this->arguments['field'];
152
153
        if (empty($fieldName)
154
            && $this->fieldService->fieldContextExists()
155
        ) {
156
            $field = $this->fieldService->getCurrentField();
157
            $fieldName = $field->getFieldName();
158
        }
159
160
        if (null === $fieldName) {
161
            throw new InvalidEntryException(
162
                'The field could not be fetched, 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.',
163
                1467624152
164
            );
165
        }
166
167
        return $fieldName;
168
    }
169
170
    /**
171
     * @return Field
172
     * @throws \Exception
173
     */
174
    protected function getField()
175
    {
176
        $formObject = $this->formService->getFormObject();
177
        $fieldName = $this->getFieldName();
178
179
        if (false === $formObject->getConfiguration()->hasField($fieldName)) {
180
            throw new EntryNotFoundException(
181
                vsprintf(
182
                    'The Form "%s" does not have a field "%s"',
183
                    [$formObject->getName(), $fieldName]
184
                ),
185
                1473084335
186
            );
187
        }
188
189
        return $formObject->getConfiguration()->getField($fieldName);
190
    }
191
192
    /**
193
     * @param FormService $service
194
     */
195
    public function injectFormService(FormService $service)
196
    {
197
        $this->formService = $service;
198
    }
199
200
    /**
201
     * @param FieldService $service
202
     */
203
    public function injectFieldService(FieldService $service)
204
    {
205
        $this->fieldService = $service;
206
    }
207
}
208