Completed
Push — unit-test-view-helpers ( 33f1c6...2824c7 )
by Romain
02:16
created

FormatMessageViewHelper::injectFormService()   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
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
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\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 FormService
47
     */
48
    protected $formService;
49
50
    /**
51
     * @var FieldService
52
     */
53
    protected $fieldService;
54
55
    /**
56
     * @inheritdoc
57
     */
58
    public function initializeArguments()
59
    {
60
        $this->registerArgument('message', 'object', 'The message which will be formatted.', true);
61
        $this->registerArgument('field', 'string', 'Name of the field which will be managed. By default, it is the field from the current `FieldViewHelper`.');
62
    }
63
64
    /**
65
     * @inheritdoc
66
     */
67
    public function render()
68
    {
69
        $message = $this->getMessage();
70
        $fieldName = $this->getFieldName();
71
        $field = $this->getField();
72
        $formObject = $this->formService->getFormObject();
73
74
        $templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
75
76
        $fieldId = ($templateVariableContainer->exists('fieldId'))
77
            ? $templateVariableContainer->get('fieldId')
78
            : StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
79
80
        $result = str_replace(
81
            [
82
                '#FIELD#',
83
                '#FIELD_ID#',
84
                '#TYPE#',
85
                '#VALIDATOR#',
86
                '#KEY#',
87
                '#MESSAGE#'
88
            ],
89
            [
90
                $fieldName,
91
                $fieldId,
92
                $this->getMessageType($message),
93
                MessageService::get()->getMessageValidationName($message),
94
                MessageService::get()->getMessageKey($message),
95
                $message->getMessage()
0 ignored issues
show
Bug introduced by
The method getMessage() does not exist on Romm\Formz\Error\FormzMessageInterface. Did you maybe mean getMessageKey()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
96
            ],
97
            $field->getSettings()->getMessageTemplate()
98
        );
99
100
        return $result;
101
    }
102
103
    /**
104
     * @return Message|FormzMessageInterface
105
     * @throws \Exception
106
     */
107
    protected function getMessage()
108
    {
109
        $message = $this->arguments['message'];
110
111
        if (false === $message instanceof Message) {
0 ignored issues
show
Bug introduced by
The class TYPO3\CMS\Extbase\Error\Message does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
112
            throw new InvalidArgumentTypeException(
113
                'The argument "message" for the view helper "' . __CLASS__ . '" must be an instance of "' . Message::class . '".',
114
                1467021406
115
            );
116
        }
117
118
        return $message;
119
    }
120
121
    /**
122
     * @param Message $message
123
     * @return string
124
     */
125
    protected function getMessageType(Message $message)
126
    {
127
        if ($message instanceof Error) {
0 ignored issues
show
Bug introduced by
The class TYPO3\CMS\Extbase\Error\Error does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
128
            $messageType = 'error';
129
        } elseif ($message instanceof Warning) {
0 ignored issues
show
Bug introduced by
The class TYPO3\CMS\Extbase\Error\Warning does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
130
            $messageType = 'warning';
131
        } elseif ($message instanceof Notice) {
0 ignored issues
show
Bug introduced by
The class TYPO3\CMS\Extbase\Error\Notice does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132
            $messageType = 'notice';
133
        } else {
134
            $messageType = 'message';
135
        }
136
137
        return $messageType;
138
    }
139
140
    /**
141
     * @return string
142
     * @throws \Exception
143
     */
144
    protected function getFieldName()
145
    {
146
        $fieldName = $this->arguments['field'];
147
148
        if (empty($fieldName)
149
            && $this->fieldService->fieldContextExists()
150
        ) {
151
            $field = $this->fieldService->getCurrentField();
152
            $fieldName = $field->getFieldName();
153
        }
154
155
        if (null === $fieldName) {
156
            throw new InvalidEntryException(
157
                '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.',
158
                1467624152
159
            );
160
        }
161
162
        return $fieldName;
163
    }
164
165
    /**
166
     * @return Field
167
     * @throws \Exception
168
     */
169
    protected function getField()
170
    {
171
        $formObject = $this->formService->getFormObject();
172
        $fieldName = $this->getFieldName();
173
174
        if (false === $formObject->getConfiguration()->hasField($fieldName)) {
175
            throw new EntryNotFoundException(
176
                vsprintf(
177
                    'The Form "%s" does not have a field "%s"',
178
                    [$formObject->getName(), $fieldName]
179
                ),
180
                1473084335
181
            );
182
        }
183
184
        return $formObject->getConfiguration()->getField($fieldName);
185
    }
186
187
    /**
188
     * @param FormService $service
189
     */
190
    public function injectFormService(FormService $service)
191
    {
192
        $this->formService = $service;
193
    }
194
195
    /**
196
     * @param FieldService $service
197
     */
198
    public function injectFieldService(FieldService $service)
199
    {
200
        $this->fieldService = $service;
201
    }
202
}
203