Completed
Push — master ( 7d660e...c11331 )
by Avtandil
02:52
created

MultiLang::getRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
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');
180
181 4
        if (strlen($locale) == 2) {
182 3
            $locales = $this->config->get('locales');
183
184 3
            if (!isset($locales[$locale])) {
185 2
                $segments    = $request->segments();
186 2
                $segments[0] = $fallback_locale;
187 2
                $url         = implode('/', $segments);
188 2
                if ($query_string = $request->server->get('QUERY_STRING')) {
189 1
                    $url .= '?' . $query_string;
190
                }
191
192 3
                return $url;
193
            }
194
        } else {
195 1
            $segments = $request->segments();
196 1
            $url      = $fallback_locale . '/' . implode('/', $segments);
197 1
            if ($query_string = $request->server->get('QUERY_STRING')) {
198
                $url .= '?' . $query_string;
199
            }
200 1
            return $url;
201
        }
202
203 1
        return null;
204
    }
205
206 1
    public function detectLocale(Request $request)
207
    {
208 1
        $locale  = $request->segment(1);
209 1
        $locales = $this->config->get('locales');
210
211 1
        if (isset($locales[$locale])) {
212 1
            return isset($locales[$locale]['locale']) ? $locales[$locale]['locale'] : $locale;
213
        }
214
215
        return $this->config->get('default_locale', 'en');
216
    }
217
218
    /**
219
     * Get texts
220
     *
221
     * @return array
222
     */
223 4
    public function getTexts()
224
    {
225
226 4
        return $this->texts;
227
    }
228
229
    /**
230
     * Set texts manually
231
     *
232
     * @param  array                                 $texts_array
233
     * @return \Longman\LaravelMultiLang\MultiLang
234
     */
235 3
    public function setTexts(array $texts_array)
236
    {
237 3
        $texts = [];
238 3
        foreach ($texts_array as $key => $value) {
239 3
            $texts[$key] = $value;
240
        }
241
242 3
        $this->texts = $texts;
243
244 3
        return $this;
245
    }
246
247
    /**
248
     * Queue missing texts
249
     *
250
     * @param  string $key
251
     * @return void
252
     */
253 4
    protected function queueToSave($key)
254
    {
255 4
        $this->new_texts[$key] = $key;
256 4
    }
257
258 2
    public function getUrl($path)
259
    {
260 2
        $locale = $this->getLocale();
261 2
        if ($locale) {
262 2
            $path = $locale . '/' . $path;
263
        }
264 2
        return $path;
265
    }
266
267 5
    public function autoSaveIsAllowed()
268
    {
269 5
        if ($this->environment == 'local' && $this->config->get('db.autosave', true)) {
270 1
            return true;
271
        }
272 5
        return false;
273
    }
274
275 18
    public function getLocale()
276
    {
277 18
        return $this->lang;
278
    }
279
280 1
    public function getLocales()
281
    {
282 1
        return $this->config->get('locales');
283
    }
284
285 3
    public function saveTexts()
286
    {
287 3
        if (empty($this->new_texts)) {
288 3
            return false;
289
        }
290
291 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...
292 3
        return true;
293
    }
294
}
295