Passed
Pull Request — master (#332)
by Arman
02:44
created

LangFactory::get()   B

Complexity

Conditions 8
Paths 17

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 15
c 1
b 0
f 0
nc 17
nop 0
dl 0
loc 31
rs 8.4444
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.9
13
 */
14
15
namespace Quantum\Libraries\Lang\Factories;
16
17
use Quantum\Libraries\Lang\Exceptions\LangException;
18
use Quantum\Config\Exceptions\ConfigException;
19
use Quantum\Di\Exceptions\DiException;
20
use Quantum\Libraries\Lang\Translator;
21
use Quantum\Libraries\Lang\Lang;
22
use Quantum\Http\Request;
23
use Quantum\Loader\Setup;
24
use ReflectionException;
25
26
/**
27
 * Class LangFactory
28
 * @package Quantum\Libraries\Lang
29
 */
30
class LangFactory
31
{
32
33
    /**
34
     * @var Lang|null Cached Lang instance
35
     */
36
    private static $instance = null;
37
38
    /**
39
     * @return Lang
40
     * @throws ConfigException
41
     * @throws LangException
42
     * @throws DiException
43
     * @throws ReflectionException
44
     */
45
    public static function get(): Lang
46
    {
47
        if (self::$instance !== null) {
48
            return self::$instance;
49
        }
50
51
        if (!config()->has('lang')) {
52
            config()->import(new Setup('config', 'lang'));
53
        }
54
55
        $isEnabled = filter_var(config()->get('lang.enabled'), FILTER_VALIDATE_BOOLEAN);
56
57
        $langSegmentIndex = (int)config()->get('lang.url_segment');
58
59
        if (!empty(route_prefix()) && $langSegmentIndex == 1) {
60
            $langSegmentIndex++;
61
        }
62
63
        $lang = Request::getSegment($langSegmentIndex);
64
65
        if (empty($lang) || !in_array($lang, (array)config()->get('lang.supported'))) {
66
            $lang = config()->get('lang.default');
67
        }
68
69
        if (!$lang) {
70
            throw LangException::misconfiguredDefaultConfig();
71
        }
72
73
        $translator = new Translator($lang);
74
75
        return self::$instance = new Lang($lang, $isEnabled, $translator);
76
    }
77
}
78