Completed
Pull Request — development (#39)
by Romain
02:14
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 TYPO3\CMS\Extbase\Error\Error;
24
use TYPO3\CMS\Extbase\Error\Message;
25
use TYPO3\CMS\Extbase\Error\Notice;
26
use TYPO3\CMS\Extbase\Error\Warning;
27
28
/**
29
 * This view helper can format the validation result messages of a field.
30
 *
31
 * It will use the message template defined for the given field, and handle
32
 * every dynamic value which can be found in the template (see below):
33
 *
34
 * #FIELD# : Name of the field;
35
 * #FIELD_ID# : Value of the `id` attribute of the field DOM element;
36
 * #VALIDATOR# : Name of the validation rule;
37
 * #TYPE#' : Type of the message (usually `error`);
38
 * #KEY#' : Key of the message (usually `default`);
39
 * #MESSAGE# : The message itself.
40
 */
41
class FormatMessageViewHelper extends AbstractViewHelper
42
{
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function initializeArguments()
48
    {
49
        $this->registerArgument('message', 'object', 'The message which will be formatted.', true);
50
        $this->registerArgument('field', 'string', 'Name of the field which will be managed. By default, it is the field from the current `FieldViewHelper`.');
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public function render()
57
    {
58
        $message = $this->getMessage();
59
        $fieldName = $this->getFieldName();
60
        $field = $this->getField();
61
        $formObject = $this->service->getFormObject();
62
63
        $templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
64
65
        $fieldId = ($templateVariableContainer->exists('fieldId'))
66
            ? $templateVariableContainer->get('fieldId')
67
            : StringService::get()->sanitizeString('formz-' . $formObject->getName() . '-' . $fieldName);
68
69
        $result = str_replace(
70
            [
71
                '#FIELD#',
72
                '#FIELD_ID#',
73
                '#TYPE#',
74
                '#VALIDATOR#',
75
                '#KEY#',
76
                '#MESSAGE#'
77
            ],
78
            [
79
                $fieldName,
80
                $fieldId,
81
                $this->getMessageType($message),
82
                MessageService::get()->getMessageValidationName($message),
83
                MessageService::get()->getMessageKey($message),
84
                $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...
85
            ],
86
            $field->getSettings()->getMessageTemplate()
87
        );
88
89
        return $result;
90
    }
91
92
    /**
93
     * @return Message|FormzMessageInterface
94
     * @throws \Exception
95
     */
96
    protected function getMessage()
97
    {
98
        $message = $this->arguments['message'];
99
100
        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...
101
            throw new InvalidArgumentTypeException(
102
                'The argument "message" for the view helper "' . __CLASS__ . '" must be an instance of "' . Message::class . '".',
103
                1467021406
104
            );
105
        }
106
107
        return $message;
108
    }
109
110
    /**
111
     * @param Message $message
112
     * @return string
113
     */
114
    protected function getMessageType(Message $message)
115
    {
116
        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...
117
            $messageType = 'error';
118
        } 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...
119
            $messageType = 'warning';
120
        } 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...
121
            $messageType = 'notice';
122
        } else {
123
            $messageType = 'message';
124
        }
125
126
        return $messageType;
127
    }
128
129
    /**
130
     * @return string
131
     * @throws \Exception
132
     */
133
    protected function getFieldName()
134
    {
135
        $fieldName = $this->arguments['field'];
136
137
        if (empty($fieldName)
138
            && $this->service->fieldContextExists()
139
        ) {
140
            $field = $this->service->getCurrentField();
141
            $fieldName = $field->getFieldName();
142
        }
143
144
        if (null === $fieldName) {
145
            throw new InvalidEntryException(
146
                '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.',
147
                1467624152
148
            );
149
        }
150
151
        return $fieldName;
152
    }
153
154
    /**
155
     * @return Field
156
     * @throws \Exception
157
     */
158
    protected function getField()
159
    {
160
        $formObject = $this->service->getFormObject();
161
        $fieldName = $this->getFieldName();
162
163
        if (false === $formObject->getConfiguration()->hasField($fieldName)) {
164
            throw new EntryNotFoundException(
165
                vsprintf(
166
                    'The Form "%s" does not have a field "%s"',
167
                    [$formObject->getName(), $fieldName]
168
                ),
169
                1473084335
170
            );
171
        }
172
173
        return $formObject->getConfiguration()->getField($fieldName);
174
    }
175
}
176