Completed
Push — unit-test-services ( 337105...93a0bd )
by Romain
02:23
created

MessageService::getMessageKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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