SamsonLocale   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 11.11%

Importance

Changes 0
Metric Value
dl 0
loc 176
ccs 4
cts 36
cp 0.1111
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 6 2
A set() 0 20 4
A get() 0 4 1
A current() 0 20 2
B parseURL() 0 29 5
1
<?php
2
namespace samson\core;
3
4
// TODO: Should moved to separate module, probably i18n
5
6
//[PHPCOMPRESSOR(remove,start)]
7
// I default locale is not defined
8 1
if (!defined('DEFAULT_LOCALE')) {
9
    // Define default locale
10 1
    define('DEFAULT_LOCALE', SamsonLocale::RU);
11 1
}
12
//[PHPCOMPRESSOR(remove,end)]
13
14
/**
15
 * Класс для поддержки локализации веб-приложения
16
 *
17
 * @author Vitaly Iegorov <[email protected]>
18
 * @package SamsonPHP 
19
 * @version 0.1.0
20
 */
21
class SamsonLocale
22
{
23
    /** Локализация по умолчанию */
24
    const DEF = DEFAULT_LOCALE;
25
    /** Украинская локализация */
26
    const UA = 'ua';
27
    /** Английская локализация */
28
    const EN = 'en';
29
    /** Русская локализация */
30
    const RU = 'ru';
31
    /** Румынская локализация */
32
    const RO = 'ro';
33
    /** Китайская локализация */
34
    const CH = 'ch';
35
    /** Французская локализация */
36
    const FR = 'fr';
37
    /** Корейская локализация */
38
    const KO = 'ko';
39
    /** Немецкая локализация */
40
    const DE = 'de';
41
    /** Испанская локализация */
42
    const ES = 'es';
43
44
    /**
45
     * Коллекция поддерживаемых локализаций
46
     * Используется для дополнительного контроля за локализациями
47
     * @var array
48
     */
49
    private static $supported = array(
50
        SamsonLocale::DEF,
51
        SamsonLocale::EN,
52
        SamsonLocale::UA,
53
        SamsonLocale::RO,
54
        SamsonLocale::CH,
55
        SamsonLocale::RU,
56
        SamsonLocale::FR,
57
        SamsonLocale::KO,
58
        SamsonLocale::DE,
59
        SamsonLocale::ES,
60
    );
61
62
    /**
63
     * Alias for binding default web-application locale
64
     * @var string
65
     */
66
    public static $defaultLocale = DEFAULT_LOCALE;
67
68
    /**
69
     * Текущая локализация веб-приложения
70
     * @var string
71
     */
72
    public static $current_locale = '';
73
74
    /**
75
     * Коллекция подключенных локализаций для текущего веб-приложения
76
     * Локаль по умолчанию RU, имеет представление пустышку - ''
77
     * @var array
78
     */
79
    public static $locales = array();
80
81
    /** @var bool Flag for leaving default locale as path placeholder */
82
    public static $leaveDefaultLocale = true;
83
84
    /**
85
     * Проверить текущей значение установленной локали, и если выставлена
86
     * не поддерживаемая локаль - установим локаль по умолчанию
87
     */
88
    public static function check()
89
    {
90
        // Проверим значение установленной текущей локализации, если оно не входит в список доступных локализаций
91
        // установим локализацию по умолчанию
92
        if (!in_array(strtolower(self::$current_locale), self::$locales)) self::$current_locale = self::DEF;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
93
    }
94
95
    /**
96
     * Установить все доступные локализации для текущего веб-приложения.
97
     * Локализацию по умолчанию, передавать не нужно, т.к. она уже включена в список
98
     * и описана в <code>SamsonLocale::DEF</code>
99
     *
100
     * Функция автоматически проверяет уже выставленное значение локализации веб-приложения
101
     * и вслучаи его отсутствия, выставляет локализацию по умолчанию
102
     *
103
     * @param array $available_locales Коллекция с доступными локализациями веб-приложения
104
     */
105
    public static function set(array $available_locales)
106
    {
107
        // Переберем локализации
108
        foreach ($available_locales as $locale) {
109
            $_locale = strtolower($locale);
110
111
            // Добавим в коллекцию доступных локализаций переданные
112
            if (in_array($_locale, self::$supported)) {
113
                // Ignore duplicare locale setting
114
                if (!in_array($_locale, self::$locales)) {
115
                    self::$locales[] = $_locale;
116
                }
117
            } // Проверим разрешаемые локали
118
            else die('Устанавливаемая локализация "' . $locale . '" - не предусмотрена в SamsonLocale');
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
119
        }
120
121
        // Проверим значение установленной текущей локализации, если оно не входит в список доступных локализаций
122
        // установим локализацию по умолчанию
123
        self::check();
124
    }
125
126
    /**
127
     * Получить все доступные локализации для текущего веб-приложения
128
     */
129
    public static function get()
130
    {
131
        return self::$locales;
132
    }
133
134 2
    /**
135
     * Установить/Получить текущую локализацию веб-приложения
136
     * @param string $locale Значение локализации веб-приложения для установки
137 2
     * @return string    Возвращается значение текущей локализации веб-приложения до момента
138
     *                    вызова данного метода
139
     */
140 2
    public static function current($locale = null)
141 2
    {
142
        // Сохраним старое значение локали
143
        $_locale = self::$current_locale;
144
145
        // If nothing is passed just return current locale
146
        if (!isset($locale)) {
147
            return $_locale;
148
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
149
        } else { // Switch locale
150
            // Save new locale
151
            self::$current_locale = strtolower($locale);
152
153
            // Запишем текущее значение локализации
154
            $_SESSION['__SAMSON_LOCALE__'] = self::$current_locale;
155
156
            // Вернем текущее значение локали сайта до момента візова метода
157
            return self::$current_locale;
158
        }
159
    }
160
161
    /**
162
     * Parse URL arguments
163
     * @param array $args Collection of URL arguments
164
     * @param bool $leaveDefaultLocale Leave default locale placeholder
165
     * @return boolean True if current locale has been changed
166
     */
167
    public static function parseURL(array &$args, $leaveDefaultLocale = true)
168
    {
169
        // Iterate defined site locales
170
        foreach (self::$locales as $locale) {
171
            // Search locale string as URL argument
172
            if (($key = array_search($locale, $args)) === 0) {
173
                // Change current locale
174
                self::current($locale);
175
176
                // If this is not default locale(empty string) - remove it from URL arguments
177
                if ($leaveDefaultLocale || $locale != self::DEF) {
178
                    // Remove argument contained locale string
179
                    unset($args[$key]);
180
181
                    // Reindex array
182
                    $args = array_values($args);
183
                }
184
185
                // Return true status
186
                return true;
187
            }
188
        }
189
190
        // If we are here - this is default locale
191
        // Switch to current web-application $default locale
192
        self::current(self::DEF);
193
194
        return false;
195
    }
196
}
197