Completed
Push — master ( cf42d1...a4e9de )
by Avtandil
02:54
created

MultiLang::getUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
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\Contracts\Cache\Factory as CacheContract;
14
use Illuminate\Database\DatabaseManager as DatabaseContract;
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\Repository
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 23
    public function __construct($environment, array $config, CacheContract $cache, DatabaseContract $db)
93
    {
94 23
        $this->environment = $environment;
95 23
        $this->cache       = $cache;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cache of type object<Illuminate\Contracts\Cache\Factory> is incompatible with the declared type object<Illuminate\Cache\Repository> of property $cache.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
96 23
        $this->db          = $db;
97
98 23
        $this->setConfig($config);
99 23
    }
100
101 23
    public function setConfig(array $config)
102
    {
103 23
        $this->config = $this->getDefaultConfig();
104
105 23
        foreach ($config as $k => $v) {
106 3
            $this->config[$k] = $v;
107 23
        }
108 23
    }
109
110 23
    public function getDefaultConfig()
111
    {
112
        $config = [
113 23
            'enabled'        => true,
114
            'locales'        => [
115
                'en' => [
116 23
                    'name'        => 'English',
117 23
                    'native_name' => 'English',
118 23
                    'default'     => true,
119 23
                ],
120 23
            ],
121 23
            'autosave'       => true,
122 23
            'cache'          => true,
123 23
            'cache_lifetime' => 1440,
124 23
            'texts_table'    => 'texts',
125 23
        ];
126 23
        return $config;
127
    }
128
129 21
    public function getConfig($key = null)
130
    {
131 21
        if ($key === null) {
132 1
            return $this->config;
133
        }
134
135 21
        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 22
    public function setLocale($lang, $default_lang = null, $texts = null)
147
    {
148 22
        if (!$lang) {
149 1
            throw new InvalidArgumentException('Locale is empty');
150
        }
151 21
        $this->lang = $lang;
152
153 21
        if ($default_lang === null) {
154 20
            $default_lang = $lang;
155 20
        }
156
157 21
        $this->default_lang = $default_lang;
158
159 21
        $this->setCacheName($lang);
160
161 21
        if (is_array($texts)) {
162 1
            $texts = new Collection($texts);
163 1
        } else {
164 20
            $texts = $this->loadTexts($this->getLocale());
165
        }
166
167 21
        $this->texts = new Collection($texts);
168 21
    }
169
170
    /**
171
     * Load texts
172
     *
173
     * @param  string  $lang
174
     * @return array
175
     */
176 20
    public function loadTexts($lang = null)
177
    {
178 20
        $cache = $this->getConfig('cache');
179
180 20
        if (!$cache || $this->cache === null || $this->environment != 'production') {
181 17
            $texts = $this->loadTextsFromDatabase($lang);
182 17
            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 7
    public function get($key)
202
    {
203
204 7
        if (empty($key)) {
205 1
            throw new InvalidArgumentException('String key not provided');
206
        }
207
208 6
        if (!$this->lang) {
209 1
            return $key;
210
        }
211
212 5
        if (!$this->texts->has($key)) {
213 4
            $this->queueToSave($key);
214 4
            return $key;
215
        }
216
217 1
        $text = $this->texts->get($key);
218
219 1
        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 1
                }
242
243 2
                return $url;
244
            }
245 1
        } 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 3
        }
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
        $status         = $this->cache->put($this->getCacheName(), $texts, $cache_lifetime);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $status is correct as $this->cache->put($this-...texts, $cache_lifetime) (which targets Illuminate\Cache\Repository::put()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
313 4
        return $status;
314
    }
315
316 20
    public function loadTextsFromDatabase($lang)
317
    {
318 20
        $texts = $lang ? $this->db->table($this->getTableName())
319 20
            ->where('lang', $lang)
320 20
            ->get(['key', 'value', 'lang', 'scope']) : $this->db->table($this->getTableName())->get(['key', 'value', 'lang', 'scope']);
321
322 20
        $array = [];
323 20
        foreach ($texts as $row) {
324 14
            $array[$row->key] = $row->value;
325 20
        }
326 20
        return $array;
327
    }
328
329 1
    public function loadTextsFromCache()
330
    {
331 1
        $texts = $this->cache->get($this->getCacheName());
332
333 1
        return $texts;
334
    }
335
336 21
    public function setCacheName($lang)
337
    {
338 21
        $this->cache_name = $this->getConfig('texts_table') . '_' . $lang;
339 21
    }
340
341 4
    public function getCacheName()
342
    {
343 4
        return $this->cache_name;
344
    }
345
346 1
    public function getUrl($path)
347
    {
348 1
        $locale = $this->getLocale();
349 1
        if ($locale) {
350 1
            $path = $locale . '/' . $path;
351 1
        }
352 1
        return $path;
353
    }
354
355 2
    public function autoSaveIsAllowed()
356
    {
357 2
        if ($this->environment == 'local' && $this->getConfig('autosave') && $this->db !== null) {
358 1
            return true;
359
        }
360 2
        return false;
361
    }
362
363 20
    public function getLocale()
364
    {
365 20
        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 3
                ]);
392 3
            }
393 3
        }
394 3
        return true;
395
    }
396
397 20
    protected function getTableName()
398
    {
399 20
        $table = $this->getConfig('texts_table');
400 20
        return $table;
401
    }
402
}
403