Lang::init()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.1795
c 0
b 0
f 0
cc 8
nc 11
nop 2
1
<?php
2
3
namespace Fabrica\Helper;
4
5
use Fabrica\Tools\Config;
6
use Fabrica\Tools\Store\Factory;
7
use Fabrica\Tools\Store\UserStore;
8
9
/**
10
 * Languages Helper Class - Handles loading strings files and the strings within them.
11
 */
12
class Lang
13
{
14
    const DEFAULT_LANGUAGE = 'en';
15
16
    /**
17
     * @var string
18
     */
19
    protected static $language  = null;
20
21
    /**
22
     * @var array
23
     */
24
    protected static $languages = [];
25
26
    /**
27
     * @var array
28
     */
29
    protected static $strings = [];
30
31
    /**
32
     * @var array
33
     */
34
    protected static $defaultStrings = [];
35
36
    /**
37
     * Get a specific string from the language file.
38
     *
39
     * @param array ...$params
40
     *
41
     * @return string
42
     */
43
    public static function get(...$params)
44
    {
45
        $string = $params[0];
46
        if (array_key_exists($string, self::$strings)) {
47
            $params[0] = self::$strings[$string];
48
            return call_user_func_array('sprintf', $params);
49
        } elseif (self::DEFAULT_LANGUAGE !== self::$language && array_key_exists($string, self::$defaultStrings)) {
50
            $params[0] = self::$defaultStrings[$string];
51
            return call_user_func_array('sprintf', $params);
52
        }
53
54
        return $string;
55
    }
56
57
    /**
58
     * Get the currently active language.
59
     *
60
     * @return string|null
61
     */
62
    public static function getLanguage()
63
    {
64
        return self::$language;
65
    }
66
67
    /**
68
     * Try and load a language, and if successful, set it for use throughout the system.
69
     *
70
     * @param $language
71
     *
72
     * @return bool
73
     */
74
    public static function setLanguage($language)
75
    {
76
        if (in_array($language, self::$languages)) {
77
            self::$language = $language;
78
            self::$strings  = self::loadLanguage();
0 ignored issues
show
Documentation Bug introduced by
It seems like self::loadLanguage() can be null. However, the property $strings is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

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

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
79
            return true;
80
        }
81
82
        return false;
83
    }
84
85
    /**
86
     * Return a list of available languages and their names.
87
     *
88
     * @return array
89
     */
90
    public static function getLanguageOptions()
91
    {
92
        $languages = [];
93
        foreach (self::$languages as $language) {
94
            $strings = include SRC_DIR . 'Languages/lang.' . $language . '.php';
95
            $languages[$language] = !empty($strings['language_name'])
96
                ? $strings['language_name'] . ' (' . $language . ')'
97
                : $language;
98
        }
99
100
        return $languages;
101
    }
102
103
    /**
104
     * Get the strings for the currently active language.
105
     *
106
     * @return string[]
107
     */
108
    public static function getStrings()
109
    {
110
        return self::$strings;
111
    }
112
113
    /**
114
     * Initialise the Language helper, try load the language file for the user's browser or the configured default.
115
     *
116
     * @param Config $config
117
     * @param string $languageForce
118
     */
119
    public static function init(Config $config, $languageForce = null)
120
    {
121
        self::$defaultStrings = self::loadLanguage(self::DEFAULT_LANGUAGE);
0 ignored issues
show
Documentation Bug introduced by
It seems like self::loadLanguage(self::DEFAULT_LANGUAGE) can be null. However, the property $defaultStrings is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

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

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
122
        self::loadAvailableLanguages();
123
124
        if ($languageForce && self::setLanguage($languageForce)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $languageForce of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
125
            return;
126
        }
127
128
        $user = null;
129
        if (!empty($_SESSION['php-censor-user-id'])) {
130
            /**
131
 * @var UserStore $userStore 
132
*/
133
            $userStore = Factory::getStore('User');
134
            $user      = $userStore->getById($_SESSION['php-censor-user-id']);
135
        }
136
137
        if ($user) {
138
            $language = $user->getLanguage();
139
            if ($user && self::setLanguage($language)) {
140
                return;
141
            }
142
        }
143
144
        // Try the installation default language:
145
        $language = $config->get('php-censor.language', self::DEFAULT_LANGUAGE);
146
        if (self::setLanguage($language)) {
147
            return;
148
        }
149
    }
150
151
    /**
152
     * Load a specific language file.
153
     *
154
     * @param string $language
155
     *
156
     * @return string[]|null
157
     */
158
    protected static function loadLanguage($language = null)
159
    {
160
        $language = $language
161
            ? $language
162
            : self::$language;
163
164
        $langFile = SRC_DIR . 'Languages/lang.' . $language . '.php';
165
166
        if (!file_exists($langFile)) {
167
            return null;
168
        }
169
170
        $strings = include $langFile;
171
        if (is_null($strings) || !is_array($strings) || !count($strings)) {
172
            return null;
173
        }
174
175
        return $strings;
176
    }
177
178
    /**
179
     * Load the names of all available languages.
180
     */
181
    protected static function loadAvailableLanguages()
182
    {
183
        $matches = [];
184
        foreach (glob(SRC_DIR . 'Languages/lang.*.php') as $file) {
185
            if (preg_match('/lang\.([a-z]{2}\-?[a-z]*)\.php/', $file, $matches)) {
186
                self::$languages[] = $matches[1];
187
            }
188
        }
189
    }
190
}
191