MessageService::getMessageValidationName()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
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\Service;
15
16
use Romm\Formz\Configuration\Form\Field\Validation\Message as FormzMessage;
17
use Romm\Formz\Error\FormzMessageInterface;
18
use Romm\Formz\Service\Traits\ExtendedSelfInstantiateTrait;
19
use TYPO3\CMS\Core\SingletonInterface;
20
use TYPO3\CMS\Core\Utility\ArrayUtility;
21
use TYPO3\CMS\Extbase\Error\Message;
22
use TYPO3\CMS\Extbase\Error\Result;
23
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
24
25
class MessageService implements SingletonInterface
26
{
27
    use ExtendedSelfInstantiateTrait;
28
29
    /**
30
     * @var Dispatcher
31
     */
32
    protected $signalSlotDispatcher;
33
34
    /**
35
     * @param Message $message
36
     * @return string
37
     */
38
    public function getMessageValidationName(Message $message)
39
    {
40
        return $message instanceof FormzMessageInterface
41
            ? $message->getValidationName()
42
            : 'unknown';
43
    }
44
45
    /**
46
     * @param Message $message
47
     * @return string
48
     */
49
    public function getMessageKey(Message $message)
50
    {
51
        return $message instanceof FormzMessageInterface
52
            ? $message->getMessageKey()
53
            : 'unknown';
54
    }
55
56
    /**
57
     * This function will go through all errors, warnings and notices and check
58
     * if they are instances of `FormzMessageInterface`. If not, they are
59
     * converted in order to have more informations that are needed later.
60
     *
61
     * @param Result $result
62
     * @param string $validationName
63
     * @return Result
64
     */
65
    public function sanitizeValidatorResult(Result $result, $validationName)
66
    {
67
        $newResult = new Result;
68
69
        $this->sanitizeValidatorResultMessages('error', $result->getFlattenedErrors(), $newResult, $validationName);
70
        $this->sanitizeValidatorResultMessages('warning', $result->getFlattenedWarnings(), $newResult, $validationName);
71
        $this->sanitizeValidatorResultMessages('notice', $result->getFlattenedNotices(), $newResult, $validationName);
72
73
        return $newResult;
74
    }
75
76
    /**
77
     * @param string $type
78
     * @param array  $messages
79
     * @param Result $newResult
80
     * @param string $validationName
81
     */
82
    protected function sanitizeValidatorResultMessages($type, array $messages, Result $newResult, $validationName)
83
    {
84
        $addMethod = 'add' . ucfirst($type);
85
        $objectType = 'Romm\\Formz\\Error\\' . ucfirst($type);
86
        $unknownCounter = 0;
87
88
        /** @var Message[] $messagesList */
89
        foreach ($messages as $path => $messagesList) {
90
            foreach ($messagesList as $message) {
91
                if (false === $message instanceof FormzMessageInterface) {
92
                    $message = new $objectType(
93
                        $message->getMessage(),
94
                        $message->getCode(),
95
                        $validationName,
96
                        'unknown-' . ++$unknownCounter,
97
                        $message->getArguments(),
98
                        $message->getTitle()
99
                    );
100
                }
101
102
                if (empty($path)) {
103
                    $newResult->$addMethod($message);
104
                } else {
105
                    $newResult->forProperty($path)->$addMethod($message);
106
                }
107
            }
108
        }
109
    }
110
111
    /**
112
     * @param array $message
113
     * @param array $arguments
114
     * @return string
115
     */
116
    public function parseMessageArray(array $message, array $arguments)
117
    {
118
        $result = (isset($message['value']) && $message['value'] !== '')
119
            ? vsprintf($message['value'], $arguments)
120
            : ContextService::get()->translate($message['key'], $message['extension'], $arguments);
121
122
        list($result) = $this->signalSlotDispatcher->dispatch(
123
            __CLASS__,
124
            'getMessage',
125
            [$result, $message, $arguments]
126
        );
127
128
        return (string)$result;
129
    }
130
131
    /**
132
     * Will return an array by considering the supported messages, and filling
133
     * the supported ones with the given values.
134
     *
135
     * @param FormzMessage[] $messages
136
     * @param array          $supportedMessages
137
     * @param bool           $canCreateNewMessages
138
     * @return array
139
     */
140
    public function filterMessages(array $messages, array $supportedMessages, $canCreateNewMessages = false)
141
    {
142
        // Adding the keys `value` and `extension` to the messages, only if it is missing.
143
        $addValueToArray = function (array &$a) {
144
            foreach ($a as $k => $v) {
145
                if (false === isset($v['value'])) {
146
                    $a[$k]['value'] = '';
147
                }
148
                if (false === isset($v['extension'])) {
149
                    $a[$k]['extension'] = '';
150
                }
151
            }
152
153
            return $a;
154
        };
155
156
        $messagesArray = [];
157
        foreach ($messages as $key => $message) {
158
            if ($message instanceof FormzMessage) {
159
                $message = $message->toArray();
160
            }
161
162
            $messagesArray[$key] = $message;
163
        }
164
165
        $addValueToArray($messagesArray);
166
        $addValueToArray($supportedMessages);
167
168
        $messagesResult = $supportedMessages;
169
170
        ArrayUtility::mergeRecursiveWithOverrule(
171
            $messagesResult,
172
            $messagesArray,
173
            (bool)$canCreateNewMessages
174
        );
175
176
        return $messagesResult;
177
    }
178
179
    /**
180
     * @param Dispatcher $signalSlotDispatcher
181
     */
182
    public function injectSignalSlotDispatcher(Dispatcher $signalSlotDispatcher)
183
    {
184
        $this->signalSlotDispatcher = $signalSlotDispatcher;
185
    }
186
}
187