Completed
Push — laravel-5 ( cdba04...7f413f )
by Andy
9s
created

MessageCachingService::createMessagesJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
crap 1
1
<?php
2
namespace JsLocalization\Caching;
3
4
use Cache;
5
use Config;
6
use Event;
7
use Lang;
8
use JsLocalization\Facades\JsLocalizationHelper;
9
10
/**
11
 * Class MessageCachingService
12
 * @package JsLocalization\Caching
13
 */
14
class MessageCachingService extends AbstractCachingService
15
{
16
17
    /**
18
     * The key used to cache the JSON encoded messages.
19
     *
20
     * @var string
21
     */
22
    const CACHE_KEY = 'js-localization-messages-json';
23
24
    /**
25
     * The key used to cache the timestamp of the last
26
     * refreshCache() call.
27
     *
28
     * @var string
29
     */
30
    const CACHE_TIMESTAMP_KEY = 'js-localization-messages-last-modified';
31
32
    
33 8
    public function __construct()
34
    {
35 8
        parent::__construct(self::CACHE_KEY, self::CACHE_TIMESTAMP_KEY);
36 8
    }
37
38
    /**
39
     * Returns the messages (already JSON encoded), fresh if wanted.
40
     * Creates the necessary cache item if necessary.
41
     *
42
     * @return string JSON encoded messages object.
43
     */
44 3
    public function getMessagesJson($noCache = false)
45
    {
46 3
        if ($noCache) {
47
            return $this->createMessagesJson();
48
        } else {
49 3
            return $this->getData();
50
        }
51
    }
52
53
    /**
54
     * Refreshes the cache item containing the JSON encoded
55
     * messages object.
56
     * Fires the 'JsLocalization.registerMessages' event.
57
     *
58
     * @return void
59
     */
60 7
    public function refreshCache()
61
    {
62 7
        Event::fire('JsLocalization.registerMessages');
63
64 7
        $messagesJSON = $this->createMessagesJson();
65 7
        $this->refreshCacheUsing($messagesJSON);
66 7
    }
67
68
    /**
69
     * @return string
70
     */
71 7
    protected function createMessagesJson()
72
    {
73 7
        $locales = $this->getLocales();
74 7
        $messageKeys = $this->getMessageKeys();
75 7
        $translatedMessages = $this->getTranslatedMessagesForLocales($messageKeys, $locales);
76
77 7
        return json_encode($translatedMessages);
78
    }
79
80
    /**
81
     * Returns the locales we need to consider.
82
     *
83
     * @return array Locales.
84
     */
85 7
    protected function getLocales()
86
    {
87 7
        return Config::get('js-localization.locales');
88
    }
89
90
    /**
91
     * Returns the translated messages for the given keys and locales.
92
     *
93
     * @param array $messageKeys
94
     * @param array $locales
95
     * @return array The translated messages as [<locale> => [ <message id> => <translation>, ... ], ...]
96
     */
97 7
    protected function getTranslatedMessagesForLocales(array $messageKeys, array $locales)
98
    {
99 7
        $translatedMessages = [];
100
101 7
        foreach ($locales as $locale) {
102 7
            if (!isset($translatedMessages[$locale])) {
103 7
                $translatedMessages[$locale] = [];
104 7
            }
105
106 7
            $translatedMessages[$locale] = $this->getTranslatedMessages($messageKeys, $locale);
107 7
        }
108
109 7
        return $translatedMessages;
110
    }
111
112
    /**
113
     * Returns the translated messages for the given keys.
114
     * 
115
     * @param array $messageKeys
116
     * @param $locale
117
     * @return array The translated messages as [ <message id> => <translation>, ... ]
118
     */
119 7
    protected function getTranslatedMessages(array $messageKeys, $locale)
120
    {
121 7
        $translatedMessages = [];
122
123 7
        foreach ($messageKeys as $key) {
124 6
            $translation = Lang::get($key, [], $locale);
125
126 6
            if (is_array($translation)) {
127 6
                $flattened = $this->flattenTranslations($translation, $key.'.');
128 6
                $translatedMessages = array_merge($translatedMessages, $flattened);
129 6
            } else {
130 6
                $translatedMessages[$key] = $translation;
131
            }
132 7
        }
133
134 7
        return $translatedMessages;
135
    }
136
137
    /**
138
     * Transforms an array of nested translation messages into a "flat" (not nested) array.
139
     *
140
     * @param array $nestedMessages
141
     * @param string $keyPrefix
142
     * @return array Flattened translations array.
143
     */
144 6
    protected function flattenTranslations(array $nestedMessages, $keyPrefix='')
145
    {
146 6
        $flattened = [];
147
148 6
        foreach ($nestedMessages as $key => $message) {
149 6
            if (is_array($message)) {
150 6
                $flattenedMessages = $this->flattenTranslations($message, $keyPrefix . $key . '.');
151 6
                $flattened = array_merge($flattened, $flattenedMessages);
152 6
            } else {
153 6
                $flattened[$keyPrefix.$key] = $message;
154
            }
155 6
        }
156
157 6
        return $flattened;
158
    }
159
160
    /**
161
     * Returns the message keys of all messages
162
     * that are supposed to be sent to the browser.
163
     *
164
     * @return array Array of message keys.
165
     */
166 7
    protected function getMessageKeys()
167
    {
168 7
        $messageKeys = Config::get('js-localization.messages');
169 7
        $messageKeys = JsLocalizationHelper::resolveMessageKeyArray($messageKeys);
170
171 7
        $messageKeys = array_unique(
172 7
            array_merge($messageKeys, JsLocalizationHelper::getAdditionalMessages())
173 7
        );
174
175 7
        return $messageKeys;
176
    }
177
}
178