LanguageManager   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
eloc 25
dl 0
loc 84
rs 10
c 2
b 0
f 2
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setCurrent() 0 3 1
A init() 0 11 2
A getUserLanguage() 0 11 3
A getCurrent() 0 3 1
A getAvailableLanguages() 0 18 4
1
<?php
2
3
/**
4
 * Keeps track of what languages are available and provides functionality for 
5
 * setting and changing the language
6
 *
7
 * @author Sam Stenvall <[email protected]>
8
 * @copyright Copyright &copy; Sam Stenvall 2014-
9
 * @license https://www.gnu.org/licenses/gpl.html The GNU General Public License v3.0
10
 */
11
class LanguageManager extends CApplicationComponent
12
{
13
14
	/**
15
	 * @var string the current language
16
	 */
17
	private $_currentLanguage;
18
19
	/**
20
	 * Initializes the component. The application language is set here. The 
21
	 * language selected is the one the user has specified, if not the 
22
	 * configured application language (which defaults to en).
23
	 */
24
	public function init()
25
	{
26
		$userLanguage = $this->getUserLanguage();
27
		$applicationLanguage = Setting::getString('language');
28
29
		if ($userLanguage)
30
			$this->_currentLanguage = $userLanguage;
31
		else
32
			$this->_currentLanguage = $applicationLanguage;
33
34
		parent::init();
35
	}
36
37
	/**
38
	 * @return string the current language
39
	 */
40
	public function getCurrent()
41
	{
42
		return $this->_currentLanguage;
43
	}
44
45
	/**
46
	 * Changes the current language
47
	 * @param string $language the new language
48
	 */
49
	public function setCurrent($language)
50
	{
51
		$this->_currentLanguage = Yii::app()->language = $language;
52
	}
53
	
54
	/**
55
	 * Returns the language the current user has specifically chosen, or null 
56
	 * if no choice has been made
57
	 * @return string|null the language or null
58
	 */
59
	private function getUserLanguage()
60
	{
61
		if (!Yii::app()->user->isGuest)
62
		{
63
			$user = User::model()->findByPk(Yii::app()->user->id);
64
65
			if ($user)
66
				return $user->language;
67
		}
68
		
69
		return null;
70
	}
71
72
	/**
73
	 * Returns a key value map of the available languages, including the source 
74
	 * language, where the key is the locale and the value is the display name
75
	 * @return array
76
	 */
77
	public static function getAvailableLanguages()
78
	{
79
		$locales = array('en');
80
		$translations = new FilesystemIterator(Yii::app()->basePath.'/messages');
81
82
		foreach ($translations as $fileInfo)
83
		{
84
			// Skip the .gitkeep file
85
			if ($fileInfo->isDir())
86
				$locales[] = $fileInfo->getFilename();
87
		}
88
89
		$languages = array();
90
91
		foreach ($locales as $language)
92
			$languages[$language] = CLocale::getInstance('en')->getLanguage($language);
93
94
		return $languages;
95
	}
96
97
}
98