Completed
Push — typo3-v8-compatibility ( ae4db2...381377 )
by Romain
02:16
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
     * @var FormService
51
     */
52
    protected $formService;
53
54
    /**
55
     * @var FieldService
56
     */
57
    protected $fieldService;
58
59
    /**
60
     * @inheritdoc
61
     */
62
    public function initializeArguments()
63
    {
64
        $this->registerArgument('message', 'object', 'The message which will be formatted.', true);
65
        $this->registerArgument('field', 'string', 'Name of the field which will be managed. By default, it is the field from the current `FieldViewHelper`.');
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71
    public function render()
72
    {
73
        $message = $this->getMessage();
74
        $fieldName = $this->getFieldName();
75
        $field = $this->getField();
76
        $formObject = $this->formService->getFormObject();
77
78
        $templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
79
80
        $fieldId = ($templateVariableContainer->exists('fieldId'))
81
            ? $templateVariableContainer->get('fieldId')
82
            : StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
83
84
        $result = str_replace(
85
            [
86
                '#FIELD#',
87
                '#FIELD_ID#',
88
                '#TYPE#',
89
                '#VALIDATOR#',
90
                '#KEY#',
91
                '#MESSAGE#'
92
            ],
93
            [
94
                $fieldName,
95
                $fieldId,
96
                $this->getMessageType($message),
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->getMessage() on line 73 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...
97
                MessageService::get()->getMessageValidationName($message),
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->getMessage() on line 73 can also be of type object<Romm\Formz\Error\FormzMessageInterface>; however, Romm\Formz\Service\Messa...MessageValidationName() 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()->getMessageKey($message),
0 ignored issues
show
Bug introduced by
It seems like $message defined by $this->getMessage() on line 73 can also be of type object<Romm\Formz\Error\FormzMessageInterface>; however, Romm\Formz\Service\MessageService::getMessageKey() 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...
99
                $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...
100
            ],
101
            $field->getSettings()->getMessageTemplate()
102
        );
103
104
        return $result;
105
    }
106
107
    /**
108
     * @return Message|FormzMessageInterface
109
     * @throws \Exception
110
     */
111
    protected function getMessage()
112
    {
113
        $message = $this->arguments['message'];
114
115
        if (false === $message instanceof Message) {
116
            throw new InvalidArgumentTypeException(
117
                'The argument "message" for the view helper "' . __CLASS__ . '" must be an instance of "' . Message::class . '".',
118
                1467021406
119
            );
120
        }
121
122
        return $message;
123
    }
124
125
    /**
126
     * @param Message $message
127
     * @return string
128
     */
129
    protected function getMessageType(Message $message)
130
    {
131
        if ($message instanceof Error) {
132
            $messageType = 'error';
133
        } elseif ($message instanceof Warning) {
134
            $messageType = 'warning';
135
        } elseif ($message instanceof Notice) {
136
            $messageType = 'notice';
137
        } else {
138
            $messageType = 'message';
139
        }
140
141
        return $messageType;
142
    }
143
144
    /**
145
     * @return string
146
     * @throws \Exception
147
     */
148
    protected function getFieldName()
149
    {
150
        $fieldName = $this->arguments['field'];
151
152
        if (empty($fieldName)
153
            && $this->fieldService->fieldContextExists()
154
        ) {
155
            $field = $this->fieldService->getCurrentField();
156
            $fieldName = $field->getFieldName();
157
        }
158
159
        if (null === $fieldName) {
160
            throw new InvalidEntryException(
161
                '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.',
162
                1467624152
163
            );
164
        }
165
166
        return $fieldName;
167
    }
168
169
    /**
170
     * @return Field
171
     * @throws \Exception
172
     */
173
    protected function getField()
174
    {
175
        $formObject = $this->formService->getFormObject();
176
        $fieldName = $this->getFieldName();
177
178
        if (false === $formObject->getConfiguration()->hasField($fieldName)) {
179
            throw new EntryNotFoundException(
180
                vsprintf(
181
                    'The Form "%s" does not have a field "%s"',
182
                    [$formObject->getName(), $fieldName]
183
                ),
184
                1473084335
185
            );
186
        }
187
188
        return $formObject->getConfiguration()->getField($fieldName);
189
    }
190
191
    /**
192
     * @param FormService $service
193
     */
194
    public function injectFormService(FormService $service)
195
    {
196
        $this->formService = $service;
197
    }
198
199
    /**
200
     * @param FieldService $service
201
     */
202
    public function injectFieldService(FieldService $service)
203
    {
204
        $this->fieldService = $service;
205
    }
206
}
207