Completed
Push — master ( c11331...67d6fa )
by Avtandil
03:06
created

MultiLang::queueToSave()   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 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
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\Http\Request;
16
use InvalidArgumentException;
17
use Longman\LaravelMultiLang\Config;
18
use Longman\LaravelMultiLang\Repository;
19
20
class MultiLang
21
{
22
    /**
23
     * Language/Locale.
24
     *
25
     * @var string
26
     */
27
    protected $lang;
28
29
    /**
30
     * System environment
31
     *
32
     * @var string
33
     */
34
    protected $environment;
35
36
    /**
37
     * Config.
38
     *
39
     * @var \Longman\LaravelMultiLang\Config
40
     */
41
    protected $config;
42
43
    /**
44
     * Repository
45
     *
46
     * @var string
47
     */
48
    protected $repository;
49
50
    /**
51
     * Texts.
52
     *
53
     * @var array
54
     */
55
    protected $texts;
56
57
    /**
58
     * Missing texts.
59
     *
60
     * @var array
61
     */
62
    protected $new_texts;
63
64
    /**
65
     * Create a new MultiLang instance.
66
     *
67
     * @param string                               $environment
68
     * @param array                                $config
69
     * @param \Illuminate\Cache\CacheManager       $cache
70
     * @param \Illuminate\Database\DatabaseManager $db
71
     */
72 23
    public function __construct($environment, array $config, Cache $cache, Database $db)
73
    {
74 23
        $this->environment = $environment;
75 23
        $this->cache       = $cache;
0 ignored issues
show
Bug introduced by
The property cache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
76 23
        $this->db          = $db;
0 ignored issues
show
Bug introduced by
The property db does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
77
78 23
        $this->setConfig($config);
79
80 23
        $this->setRepository(new Repository($this->config, $cache, $db));
81 23
    }
82
83 23
    public function setConfig(array $config)
84
    {
85 23
        $this->config = new Config($config);
86 23
        return $this;
87
    }
88
89 23
    public function setRepository(Repository $repository)
90
    {
91 23
        $this->repository = $repository;
0 ignored issues
show
Documentation Bug introduced by
It seems like $repository of type object<Longman\LaravelMultiLang\Repository> is incompatible with the declared type string of property $repository.

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...
92 23
        return $this;
93
    }
94
95 2
    public function getRepository()
96
    {
97 2
        return $this->repository;
98
    }
99
100
    /**
101
     * Set locale and load texts
102
     *
103
     * @param  string $lang
104
     * @param  array  $texts
105
     * @return void
106
     */
107 21
    public function setLocale($lang, array $texts = null)
108
    {
109 21
        if (!$lang) {
110 1
            throw new InvalidArgumentException('Locale is empty');
111
        }
112 20
        $this->lang = $lang;
113
114 20
        if (!is_array($texts)) {
115 17
            $texts = $this->loadTexts($this->getLocale());
116
        }
117
118 20
        $this->texts = $texts;
119 20
    }
120
121
    /**
122
     * Load texts
123
     *
124
     * @param  string  $lang
125
     * @return array
126
     */
127 17
    public function loadTexts($lang)
128
    {
129 17
        if ($this->environment != 'production' || $this->config->get('cache.enabled', true) === false) {
130 15
            $texts = $this->repository->loadFromDatabase($lang);
0 ignored issues
show
Bug introduced by
The method loadFromDatabase cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
131 15
            return $texts;
132
        }
133
134 3
        if ($this->repository->existsInCache($lang)) {
0 ignored issues
show
Bug introduced by
The method existsInCache cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
135
            $texts = $this->repository->loadFromCache($lang);
0 ignored issues
show
Bug introduced by
The method loadFromCache cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
136
        } else {
137 3
            $texts = $this->repository->loadFromDatabase($lang);
0 ignored issues
show
Bug introduced by
The method loadFromDatabase cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
138 3
            $this->repository->storeInCache($lang, $texts);
0 ignored issues
show
Bug introduced by
The method storeInCache cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
139
        }
140
141 3
        return $texts;
142
    }
143
144
    /**
145
     * Get translated text
146
     *
147
     * @param  string   $key
148
     * @return string
149
     */
150 8
    public function get($key)
151
    {
152
153 8
        if (empty($key)) {
154 1
            throw new InvalidArgumentException('String key not provided');
155
        }
156
157 7
        if (!$this->lang) {
158 1
            return $key;
159
        }
160
161 6
        if (!isset($this->texts[$key])) {
162 4
            $this->queueToSave($key);
163 4
            return $key;
164
        }
165
166 2
        $text = $this->texts[$key];
167
168 2
        return $text;
169
    }
170
171
    /**
172
     * Get texts
173
     *
174
     * @return array
175
     */
176 4
    public function getRedirectUrl(Request $request)
177
    {
178 4
        $locale          = $request->segment(1);
179 4
        $fallback_locale = $this->config->get('default_locale', 'en');
180 4
        $exclude_segments = $this->config->get('exclude_segments', []);
181 4
        if (in_array($locale, $exclude_segments)) {
182
            return null;
183
        }
184
185 4
        if (strlen($locale) == 2) {
186 3
            $locales = $this->config->get('locales', []);
187
188 3
            if (!isset($locales[$locale])) {
189 2
                $segments    = $request->segments();
190 2
                $segments[0] = $fallback_locale;
191 2
                $url         = implode('/', $segments);
192 2
                if ($query_string = $request->server->get('QUERY_STRING')) {
193 1
                    $url .= '?' . $query_string;
194
                }
195
196 3
                return $url;
197
            }
198
        } else {
199 1
            $segments = $request->segments();
200 1
            $url      = $fallback_locale . '/' . implode('/', $segments);
201 1
            if ($query_string = $request->server->get('QUERY_STRING')) {
202
                $url .= '?' . $query_string;
203
            }
204 1
            return $url;
205
        }
206
207 1
        return null;
208
    }
209
210 1
    public function detectLocale(Request $request)
211
    {
212 1
        $locale  = $request->segment(1);
213 1
        $locales = $this->config->get('locales');
214
215 1
        if (isset($locales[$locale])) {
216 1
            return isset($locales[$locale]['locale']) ? $locales[$locale]['locale'] : $locale;
217
        }
218
219
        return $this->config->get('default_locale', 'en');
220
    }
221
222
    /**
223
     * Get texts
224
     *
225
     * @return array
226
     */
227 4
    public function getTexts()
228
    {
229
230 4
        return $this->texts;
231
    }
232
233
    /**
234
     * Set texts manually
235
     *
236
     * @param  array                                 $texts_array
237
     * @return \Longman\LaravelMultiLang\MultiLang
238
     */
239 3
    public function setTexts(array $texts_array)
240
    {
241 3
        $texts = [];
242 3
        foreach ($texts_array as $key => $value) {
243 3
            $texts[$key] = $value;
244
        }
245
246 3
        $this->texts = $texts;
247
248 3
        return $this;
249
    }
250
251
    /**
252
     * Queue missing texts
253
     *
254
     * @param  string $key
255
     * @return void
256
     */
257 4
    protected function queueToSave($key)
258
    {
259 4
        $this->new_texts[$key] = $key;
260 4
    }
261
262 2
    public function getUrl($path)
263
    {
264 2
        $locale = $this->getLocale();
265 2
        if ($locale) {
266 2
            $path = $locale . '/' . $path;
267
        }
268 2
        return $path;
269
    }
270
271 5
    public function autoSaveIsAllowed()
272
    {
273 5
        if ($this->environment == 'local' && $this->config->get('db.autosave', true)) {
274 1
            return true;
275
        }
276 5
        return false;
277
    }
278
279 18
    public function getLocale()
280
    {
281 18
        return $this->lang;
282
    }
283
284 1
    public function getLocales()
285
    {
286 1
        return $this->config->get('locales');
287
    }
288
289 3
    public function saveTexts()
290
    {
291 3
        if (empty($this->new_texts)) {
292 3
            return false;
293
        }
294
295 3
        $this->repository->save($this->new_texts);
0 ignored issues
show
Bug introduced by
The method save cannot be called on $this->repository (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
296 3
        return true;
297
    }
298
}
299