Test Setup Failed
Pull Request — developer (#249)
by Arkadiusz
06:57
created

Language::jstranslate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 3
1
<?php
2
/**
3
 * Language controller class.
4
 *
5
 * @copyright YetiForce Sp. z o.o.
6
 * @license   YetiForce Public License 3.0 (licenses/LicenseEN.txt or yetiforce.com)
7
 * @author    Mariusz Krzaczkowski <[email protected]>
8
 */
9
10
namespace App;
11
12
class Language
0 ignored issues
show
Coding Style introduced by
Language does not seem to conform to the naming convention (Utils?$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
13
{
14
	/**
15
	 * Language files format.
16
	 */
17
	const FORMAT = 'json';
18
19
	//Contains module language translations
20
	protected static $languageContainer = [];
21
	protected static $modules = false;
22
23
	/**
24
	 * Functions that gets translated string.
25
	 *
26
	 * @param string $key             - string which need to be translated
27
	 * @param string $module          - module scope in which the translation need to be check
28
	 * @param string $currentLanguage
29
	 *
30
	 * @return string - translated string
31
	 */
32
	public static function translate(string $key, string $module = 'Basic', string $currentLanguage = ''): string
33
	{
34
		if (empty($currentLanguage)) {
35
			$currentLanguage = static::getLanguage();
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $currentLanguage. This often makes code more readable.
Loading history...
36
		}
37
		//decoding for Start Date & Time and End Date & Time
38
		if (!\is_array($key)) {
39
			$key = html_entity_decode($key);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $key. This often makes code more readable.
Loading history...
40
		}
41
		$translatedString = static::getLanguageTranslatedString($currentLanguage, $key, $module);
0 ignored issues
show
Bug introduced by
It seems like $key can also be of type array; however, App\Language::getLanguageTranslatedString() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
42
		// label not found in users language pack, then check in the default language pack(config.inc.php)
43
		if (null === $translatedString) {
44
			$defaultLanguage = Config::get('language');
45
			if (!empty($defaultLanguage) && 0 !== strcasecmp($defaultLanguage, $currentLanguage)) {
46
				$translatedString = static::getLanguageTranslatedString($defaultLanguage, $key, $module);
0 ignored issues
show
Bug introduced by
It seems like $key can also be of type array; however, App\Language::getLanguageTranslatedString() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
47
			}
48
		}
49
50
		// If translation is not found then return label
51
		if (null === $translatedString) {
52
			$translatedString = $key;
53
		}
54
		return $translatedString;
55
	}
56
57
	/**
58
	 * Functions that gets translated string by $args.
59
	 *
60
	 * @param string $key        - string which need to be translated
61
	 * @param string $moduleName - module scope in which the translation need to be check
62
	 *
63
	 * @return string - translated string
64
	 */
65
	public static function translateArgs(string $key, string $moduleName = 'Basic'): string
66
	{
67
		$formattedString = static::translate($key, $moduleName);
68
		$args = \array_slice(\func_get_args(), 2);
69
		if (\is_array($args) && !empty($args)) {
70
			$formattedString = \call_user_func_array('vsprintf', [$formattedString, $args]);
71
		}
72
		return $formattedString;
73
	}
74
75
	/**
76
	 * Function that returns current language.
77
	 *
78
	 * @return string
79
	 */
80
	public static function getLanguage()
81
	{
82
		$userInstance = User::getUser();
83
		$language = '';
0 ignored issues
show
Unused Code introduced by
$language is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
84
		if ($userInstance && $userInstance->has('language') && !empty($userInstance->get('language'))) {
85
			$language = $userInstance->get('language');
86
		} else {
87
			$language = Config::get('language');
88
		}
89
		return $language;
90
	}
91
92
	/**
93
	 * Function returns language specific translated string.
94
	 *
95
	 * @param string $language - en_us etc
96
	 * @param string $key      - label
97
	 * @param string $module   - module name
98
	 *
99
	 * @return string translated string or null if translation not found
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
100
	 */
101
	public static function getLanguageTranslatedString(string $language, string $key, string $module = 'Basic')
102
	{
103
		$moduleStrings = self::getModuleStringsFromFile($language, $module);
104
		if (!empty($moduleStrings['php'][$key])) {
105
			return stripslashes($moduleStrings['php'][$key]);
106
		}
107
108
		$commonStrings = self::getModuleStringsFromFile($language);
109
		if (!empty($commonStrings['php'][$key])) {
110
			return stripslashes($commonStrings['php'][$key]);
111
		}
112
		return null;
113
	}
114
115
	public static function getModuleStringsFromFile(string $language, string $module = 'Basic')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
116
	{
117
		if (empty(self::$languageContainer[$language][$module])) {
118
			static::loadLanguageFile($language, $module);
119
		}
120
		if (isset(self::$languageContainer[$language][$module])) {
121
			return self::$languageContainer[$language][$module];
122
		}
123
		return [];
124
	}
125
126
	/**
127
	 * Load language file from JSON.
128
	 *
129
	 * @param string $language
130
	 * @param string $moduleName
131
	 *
132
	 * @return void
133
	 */
134
	public static function loadLanguageFile(string $language, string $moduleName = 'Basic')
135
	{
136
		if (!isset(static::$languageContainer[$language][$moduleName])) {
137
			static::$languageContainer[$language][$moduleName] = [];
138
			$file = \DIRECTORY_SEPARATOR . 'languages' . \DIRECTORY_SEPARATOR . $language . \DIRECTORY_SEPARATOR . $moduleName . '.' . static::FORMAT;
139
			$langFile = ROOT_DIRECTORY . $file;
140
			if (file_exists($langFile)) {
141
				static::$languageContainer[$language][$moduleName] = Json::decode(file_get_contents($langFile), true) ?? [];
142
				Cache::save('LanguageFiles', $language . $moduleName, static::$languageContainer[$language][$moduleName], Cache::LONG);
143
			}
144
		} elseif (Cache::has('LanguageFiles', $language . $moduleName)) {
145
			static::$languageContainer[$language][$moduleName] = Cache::get('LanguageFiles', $language . $moduleName);
146
		}
147
	}
148
149
	/**
150
	 * Functions that gets translated string for Client side.
151
	 *
152
	 * @param <String> $key      - string which need to be translated
0 ignored issues
show
Documentation introduced by
The doc-type <String> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
153
	 * @param <String> $module   - module scope in which the translation need to be check
0 ignored issues
show
Documentation introduced by
The doc-type <String> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
154
	 * @param mixed    $language
155
	 *
156
	 * @return <String> - translated string
0 ignored issues
show
Documentation introduced by
The doc-type <String> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
157
	 */
158
	public static function jstranslate($language, $key, $module = 'Basic')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
159
	{
160
		$moduleStrings = self::getModuleStringsFromFile($language, $module);
161
		if (!empty($moduleStrings['js'][$key])) {
162
			return $moduleStrings['js'][$key];
163
		}
164
165
		$commonStrings = self::getModuleStringsFromFile($language);
166
		if (!empty($commonStrings['js'][$key])) {
167
			return $commonStrings['js'][$key];
168
		}
169
		return $key;
170
	}
171
172
	/**
173
	 * Function to returns all language information.
174
	 *
175
	 * @return string[]
176
	 */
177
	public static function getAllLanguages()
178
	{
179
		return Config::$languages;
180
	}
181
182
	/**
183
	 * Function that returns current language short name.
184
	 *
185
	 * @return <String> -
0 ignored issues
show
Documentation introduced by
The doc-type <String> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
186
	 */
187
	public static function getShortLanguageName()
188
	{
189
		$language = self::getLanguage();
190
		return substr($language, 0, 2);
191
	}
192
193
	/**
194
	 * Function returns module strings.
195
	 *
196
	 * @param <String> $module - module Name
0 ignored issues
show
Documentation introduced by
The doc-type <String> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
197
	 * @param  <String> languageStrings or jsLanguageStrings
198
	 * @param mixed $type
199
	 *
200
	 * @return <Array>
0 ignored issues
show
Documentation introduced by
The doc-type <Array> could not be parsed: Unknown type name "<" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
201
	 */
202
	public static function export($module, $type = 'php')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
203
	{
204
		$language = self::getLanguage();
205
		$exportLangString = [];
206
207
		$moduleStrings = self::getModuleStringsFromFile($language, $module);
208
		if (!empty($moduleStrings[$type])) {
209
			$exportLangString = $moduleStrings[$type];
210
		}
211
212
		$commonStrings = self::getModuleStringsFromFile($language);
213
		if (!empty($commonStrings[$type])) {
214
			$exportLangString += $commonStrings[$type];
215
		}
216
		return $exportLangString;
217
	}
218
219
	public static function translateModule($module)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
220
	{
221
		if (!self::$modules) {
222
			$userInstance = User::getUser();
223
			self::$modules = $userInstance->getModulesList();
224
		}
225
		return self::$modules[$module] ?? $module;
226
	}
227
}
228