Completed
Pull Request — laravel-5 (#54)
by
unknown
15:49
created

MessageCachingService::createMessagesJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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