Completed
Push — master ( c3a0f7...1d25b5 )
by Avtandil
03:06
created

MultiLang::setCacheName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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
     * System environment
30
     *
31
     * @var string
32
     */
33
    protected $environment;
34
35
    /**
36
     * The instance of the cache.
37
     *
38
     * @var \Illuminate\Cache\CacheManager
39
     */
40
    protected $cache;
41
42
    /**
43
     * Config.
44
     *
45
     * @var array
46
     */
47
    protected $config;
48
49
    /**
50
     * The instance of the database.
51
     *
52
     * @var \Illuminate\Database\DatabaseManager
53
     */
54
    protected $db;
55
56
    /**
57
     * Name of the cache.
58
     *
59
     * @var string
60
     */
61
    protected $cache_name;
62
63
    /**
64
     * Texts collection.
65
     *
66
     * @var \Illuminate\Support\Collection
67
     */
68
    protected $texts;
69
70
    /**
71
     * Missing texts.
72
     *
73
     * @var array
74
     */
75
    protected $new_texts;
76
77
    /**
78
     * Create a new MultiLang instance.
79
     *
80
     * @param  string                               $environment
81
     * @param  array                                $config
82
     * @param  \Illuminate\Cache\CacheManager       $cache
83
     * @param  \Illuminate\Database\DatabaseManager $db
84
     */
85 25
    public function __construct($environment, array $config, Cache $cache, Database $db)
86
    {
87 25
        $this->environment = $environment;
88 25
        $this->cache       = $cache;
89 25
        $this->db          = $db;
90
91 25
        $this->setConfig($config);
92 25
    }
93
94 25
    public function setConfig(array $config)
95
    {
96 25
        $this->config = $this->getDefaultConfig();
97
98 25
        foreach ($config as $k => $v) {
99 5
            $this->config[$k] = $v;
100
        }
101 25
    }
102
103 25
    public function getDefaultConfig()
104
    {
105
        $config = [
106 25
            'enabled'        => true,
107
            'locales'        => [
108
                'en' => [
109
                    'name'        => 'English',
110
                    'native_name' => 'English',
111
                ],
112
            ],
113
            'default_locale' => 'en',
114
            'autosave'       => true,
115
            'cache'          => true,
116
            'cache_lifetime' => 1440,
117
            'texts_table'    => 'texts',
118
        ];
119 25
        return $config;
120
    }
121
122 22
    public function getConfig($key = null)
123
    {
124 22
        if ($key === null) {
125 1
            return $this->config;
126
        }
127
128 22
        return isset($this->config[$key]) ? $this->config[$key] : null;
129
    }
130
131
    /**
132
     * Set locale and load texts
133
     *
134
     * @param  string $lang
135
     * @param  string $default_lang
0 ignored issues
show
Bug introduced by
There is no parameter named $default_lang. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
136
     * @param  array  $texts
137
     * @return void
138
     */
139 23
    public function setLocale($lang, $texts = null)
140
    {
141 23
        if (!$lang) {
142 1
            throw new InvalidArgumentException('Locale is empty');
143
        }
144 22
        $this->lang = $lang;
145
146 22
        $this->setCacheName($lang);
147
148 22
        if (is_array($texts)) {
149 1
            $texts = new Collection($texts);
150
        } else {
151 21
            $texts = $this->loadTexts($this->getLocale());
152
        }
153
154 22
        $this->texts = new Collection($texts);
155 22
    }
156
157
158
    /**
159
     * Load texts
160
     *
161
     * @param  string  $lang
162
     * @return array
163
     */
164 21
    public function loadTexts($lang = null)
165
    {
166 21
        $cache = $this->getConfig('cache');
167
168 21
        if (!$cache || $this->cache === null || $this->environment != 'production') {
169 18
            $texts = $this->loadTextsFromDatabase($lang);
170 18
            return $texts;
171
        }
172
173 4
        if ($this->mustLoadFromCache()) {
174
            $texts = $this->loadTextsFromCache();
175
        } else {
176 4
            $texts = $this->loadTextsFromDatabase($lang);
177 4
            $this->storeTextsInCache($texts);
178
        }
179
180 4
        return $texts;
181
    }
182
183
    /**
184
     * Get translated text
185
     *
186
     * @param  string   $key
187
     * @return string
188
     */
189 8
    public function get($key)
190
    {
191
192 8
        if (empty($key)) {
193 1
            throw new InvalidArgumentException('String key not provided');
194
        }
195
196 7
        if (!$this->lang) {
197 1
            return $key;
198
        }
199
200 6
        if (!$this->texts->has($key)) {
201 5
            $this->queueToSave($key);
202 5
            return $key;
203
        }
204
205 1
        $text = $this->texts->get($key);
206
207 1
        return $text;
208
    }
209
210
    /**
211
     * Get texts
212
     *
213
     * @return array
214
     */
215 4
    public function getRedirectUrl(Request $request)
216
    {
217 4
        $locale          = $request->segment(1);
218 4
        $fallback_locale = $this->getConfig('default_locale');
219
220
221 4
        if (strlen($locale) == 2) {
222 3
            $locales = $this->getConfig('locales');
223
224 3
            if (!isset($locales[$locale])) {
225 2
                $segments    = $request->segments();
226 2
                $segments[0] = $fallback_locale;
227 2
                $url         = implode('/', $segments);
228 2
                if ($query_string = $request->server->get('QUERY_STRING')) {
229 1
                    $url .= '?' . $query_string;
230
                }
231
232 3
                return $url;
233
            }
234
        } else {
235 1
            $segments = $request->segments();
236 1
            $url      = $fallback_locale . '/' . implode('/', $segments);
237 1
            if ($query_string = $request->server->get('QUERY_STRING')) {
238
                $url .= '?' . $query_string;
239
            }
240 1
            return $url;
241
        }
242
243 1
        return null;
244
    }
245
246 1
    public function detectLocale(Request $request)
247
    {
248 1
        $locale          = $request->segment(1);
249 1
        $locales = $this->getConfig('locales');
250
251 1
        if (isset($locales[$locale])) {
252 1
            return $locale;
253
        }
254
255
        $fallback_locale = $this->getConfig('default_locale');
0 ignored issues
show
Unused Code introduced by
$fallback_locale is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
256
        return $locale;
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 5
    protected function queueToSave($key)
295
    {
296 5
        $this->new_texts[$key] = $key;
297 5
    }
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 21
    public function loadTextsFromDatabase($lang)
317
    {
318 21
        $texts = $lang ? $this->db->table($this->getTableName())
319 21
            ->where('lang', $lang)
320 21
            ->get(['key', 'value', 'lang', 'scope']) : $this->db->table($this->getTableName())->get(['key', 'value', 'lang', 'scope']);
321
322 21
        $array = [];
323 21
        foreach ($texts as $row) {
324 16
            $array[$row->key] = $row->value;
325
        }
326 21
        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 22
    public function setCacheName($lang)
337
    {
338 22
        $this->cache_name = $this->getConfig('texts_table') . '_' . $lang;
339 22
    }
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 21
    public function getLocale()
364
    {
365 21
        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 21
    protected function getTableName()
398
    {
399 21
        $table = $this->getConfig('texts_table');
400 21
        return $table;
401
    }
402
}
403