Completed
Push — master ( 48e288...c3a0f7 )
by Avtandil
03:18
created

MultiLang::autoSaveIsAllowed()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.2
cc 4
eloc 4
nc 2
nop 0
crap 4
1
<?php
2
/*
3
 * This file is part of the Laravel MultiLang package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\LaravelMultiLang;
12
13
use Illuminate\Cache\CacheManager as Cache;
14
use Illuminate\Database\DatabaseManager as Database;
15
use Illuminate\Support\Collection;
16
use Illuminate\Http\Request;
17
use InvalidArgumentException;
18
19
class MultiLang
20
{
21
    /**
22
     * Language/Locale.
23
     *
24
     * @var string
25
     */
26
    protected $lang;
27
28
    /**
29
     * Default Language/Locale.
30
     *
31
     * @var string
32
     */
33
    protected $default_lang;
34
35
    /**
36
     * System environment
37
     *
38
     * @var string
39
     */
40
    protected $environment;
41
42
    /**
43
     * The instance of the cache.
44
     *
45
     * @var \Illuminate\Cache\CacheManager
46
     */
47
    protected $cache;
48
49
    /**
50
     * Config.
51
     *
52
     * @var array
53
     */
54
    protected $config;
55
56
    /**
57
     * The instance of the database.
58
     *
59
     * @var \Illuminate\Database\DatabaseManager
60
     */
61
    protected $db;
62
63
    /**
64
     * Name of the cache.
65
     *
66
     * @var string
67
     */
68
    protected $cache_name;
69
70
    /**
71
     * Texts collection.
72
     *
73
     * @var \Illuminate\Support\Collection
74
     */
75
    protected $texts;
76
77
    /**
78
     * Missing texts.
79
     *
80
     * @var array
81
     */
82
    protected $new_texts;
83
84
    /**
85
     * Create a new MultiLang instance.
86
     *
87
     * @param  string                               $environment
88
     * @param  array                                $config
89
     * @param  \Illuminate\Cache\CacheManager       $cache
90
     * @param  \Illuminate\Database\DatabaseManager $db
91
     */
92 25
    public function __construct($environment, array $config, Cache $cache, Database $db)
93
    {
94 25
        $this->environment = $environment;
95 25
        $this->cache       = $cache;
96 25
        $this->db          = $db;
97
98 25
        $this->setConfig($config);
99 25
    }
100
101 25
    public function setConfig(array $config)
102
    {
103 25
        $this->config = $this->getDefaultConfig();
104
105 25
        foreach ($config as $k => $v) {
106 5
            $this->config[$k] = $v;
107
        }
108 25
    }
109
110 25
    public function getDefaultConfig()
111
    {
112
        $config = [
113 25
            'enabled'        => true,
114
            'locales'        => [
115
                'en' => [
116
                    'name'        => 'English',
117
                    'native_name' => 'English',
118
                    'default'     => true,
119
                ],
120
            ],
121
            'autosave'       => true,
122
            'cache'          => true,
123
            'cache_lifetime' => 1440,
124
            'texts_table'    => 'texts',
125
        ];
126 25
        return $config;
127
    }
128
129 23
    public function getConfig($key = null)
130
    {
131 23
        if ($key === null) {
132 1
            return $this->config;
133
        }
134
135 23
        return isset($this->config[$key]) ? $this->config[$key] : null;
136
    }
137
138
    /**
139
     * Set locale and load texts
140
     *
141
     * @param  string $lang
142
     * @param  string $default_lang
143
     * @param  array  $texts
144
     * @return void
145
     */
146 24
    public function setLocale($lang, $default_lang = null, $texts = null)
147
    {
148 24
        if (!$lang) {
149 1
            throw new InvalidArgumentException('Locale is empty');
150
        }
151 23
        $this->lang = $lang;
152
153 23
        if ($default_lang === null) {
154 22
            $default_lang = $lang;
155
        }
156
157 23
        $this->default_lang = $default_lang;
158
159 23
        $this->setCacheName($lang);
160
161 23
        if (is_array($texts)) {
162 3
            $texts = new Collection($texts);
163
        } else {
164 22
            $texts = $this->loadTexts($this->getLocale());
165
        }
166
167 23
        $this->texts = new Collection($texts);
168 23
    }
169
170
    /**
171
     * Load texts
172
     *
173
     * @param  string  $lang
174
     * @return array
175
     */
176 22
    public function loadTexts($lang = null)
177
    {
178 22
        $cache = $this->getConfig('cache');
179
180 22
        if (!$cache || $this->cache === null || $this->environment != 'production') {
181 19
            $texts = $this->loadTextsFromDatabase($lang);
182 19
            return $texts;
183
        }
184
185 4
        if ($this->mustLoadFromCache()) {
186
            $texts = $this->loadTextsFromCache();
187
        } else {
188 4
            $texts = $this->loadTextsFromDatabase($lang);
189 4
            $this->storeTextsInCache($texts);
190
        }
191
192 4
        return $texts;
193
    }
194
195
    /**
196
     * Get translated text
197
     *
198
     * @param  string   $key
199
     * @return string
200
     */
201 8
    public function get($key)
202
    {
203
204 8
        if (empty($key)) {
205 1
            throw new InvalidArgumentException('String key not provided');
206
        }
207
208 7
        if (!$this->lang) {
209 1
            return $key;
210
        }
211
212 6
        if (!$this->texts->has($key)) {
213 4
            $this->queueToSave($key);
214 4
            return $key;
215
        }
216
217 2
        $text = $this->texts->get($key);
218
219 2
        return $text;
220
    }
221
222
    /**
223
     * Get texts
224
     *
225
     * @return array
226
     */
227 4
    public function getRedirectUrl(Request $request)
228
    {
229 4
        $locale          = $request->segment(1);
230 4
        $fallback_locale = $this->default_lang;
231
232 4
        if (strlen($locale) == 2) {
233 3
            $locales = $this->getConfig('locales');
234
235 3
            if (!isset($locales[$locale])) {
236 2
                $segments    = $request->segments();
237 2
                $segments[0] = $fallback_locale;
238 2
                $url         = implode('/', $segments);
239 2
                if ($query_string = $request->server->get('QUERY_STRING')) {
240 1
                    $url .= '?' . $query_string;
241
                }
242
243 3
                return $url;
244
            }
245
        } else {
246 1
            $segments = $request->segments();
247 1
            $url      = $fallback_locale . '/' . implode('/', $segments);
248 1
            if ($query_string = $request->server->get('QUERY_STRING')) {
249
                $url .= '?' . $query_string;
250
            }
251 1
            return $url;
252
        }
253
254 1
        return null;
255
    }
256
257
258
259
    /**
260
     * Get texts
261
     *
262
     * @return array
263
     */
264 4
    public function getTexts()
265
    {
266
267 4
        return $this->texts->toArray();
268
    }
269
270
    /**
271
     * Set texts manually
272
     *
273
     * @param  array                                 $texts_array
274
     * @return \Longman\LaravelMultiLang\MultiLang
275
     */
276 3
    public function setTexts(array $texts_array)
277
    {
278 3
        $texts = [];
279 3
        foreach ($texts_array as $key => $value) {
280 3
            $texts[$key] = $value;
281
        }
282
283 3
        $this->texts = new Collection($texts);
284
285 3
        return $this;
286
    }
287
288
    /**
289
     * Queue missing texts
290
     *
291
     * @param  string $key
292
     * @return void
293
     */
294 4
    protected function queueToSave($key)
295
    {
296 4
        $this->new_texts[$key] = $key;
297 4
    }
298
299
    /**
300
     * Check if we must load texts from cache
301
     *
302
     * @return bool
303
     */
304 4
    public function mustLoadFromCache()
305
    {
306 4
        return $this->cache->has($this->getCacheName());
307
    }
308
309 4
    protected function storeTextsInCache(array $texts)
310
    {
311 4
        $cache_lifetime = $this->getConfig('cache_lifetime');
312 4
        $this->cache->put($this->getCacheName(), $texts, $cache_lifetime);
313 4
        return $this;
314
    }
315
316 22
    public function loadTextsFromDatabase($lang)
317
    {
318 22
        $texts = $lang ? $this->db->table($this->getTableName())
319 22
            ->where('lang', $lang)
320 22
            ->get(['key', 'value', 'lang', 'scope']) : $this->db->table($this->getTableName())->get(['key', 'value', 'lang', 'scope']);
321
322 22
        $array = [];
323 22
        foreach ($texts as $row) {
324 14
            $array[$row->key] = $row->value;
325
        }
326 22
        return $array;
327
    }
328
329 1
    public function loadTextsFromCache()
330
    {
331 1
        $texts = $this->cache->get($this->getCacheName());
0 ignored issues
show
Bug introduced by
The method get() cannot be called from this context as it is declared protected in class Illuminate\Cache\CacheManager.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
332
333 1
        return $texts;
334
    }
335
336 23
    public function setCacheName($lang)
337
    {
338 23
        $this->cache_name = $this->getConfig('texts_table') . '_' . $lang;
339 23
    }
340
341 4
    public function getCacheName()
342
    {
343 4
        return $this->cache_name;
344
    }
345
346 2
    public function getUrl($path)
347
    {
348 2
        $locale = $this->getLocale();
349 2
        if ($locale) {
350 2
            $path = $locale . '/' . $path;
351
        }
352 2
        return $path;
353
    }
354
355 4
    public function autoSaveIsAllowed()
356
    {
357 4
        if ($this->environment == 'local' && $this->getConfig('autosave') && $this->db !== null) {
358 1
            return true;
359
        }
360 4
        return false;
361
    }
362
363 22
    public function getLocale()
364
    {
365 22
        return $this->lang;
366
    }
367
368 3
    public function saveTexts()
369
    {
370 3
        if (empty($this->new_texts)) {
371 3
            return false;
372
        }
373
374 3
        $table = $this->getTableName();
375 3
        $locales = $this->getConfig('locales');
376 3
        foreach ($this->new_texts as $k => $v) {
377 3
            foreach ($locales as $lang => $locale_data) {
378 3
                $exists = $this->db->table($table)->where([
379 3
                    'key'  => $k,
380 3
                    'lang' => $lang,
381 3
                ])->first();
382
383 3
                if ($exists) {
384 1
                    continue;
385
                }
386
387 3
                $this->db->table($table)->insert([
388 3
                    'key'   => $k,
389 3
                    'lang'  => $lang,
390 3
                    'value' => $v,
391
                ]);
392
            }
393
        }
394 3
        return true;
395
    }
396
397 22
    protected function getTableName()
398
    {
399 22
        $table = $this->getConfig('texts_table');
400 22
        return $table;
401
    }
402
}
403