Completed
Push — master ( 6a42d7...721c1d )
by Vitaly
16:19 queued 05:23
created

shortcuts.php ➔ url_build()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 18
ccs 0
cts 7
cp 0
crap 20
rs 9.2
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>
4
 * on 24.04.14 at 17:58
5
 */
6
7
// Global namespace
8
9
10
/**
11
 * System(Система) - Получить объект для работы с ядром системы
12
 * @return samson\core\Core Ядро системы
13
 * @deprecated Use $this->system in module context
14
 */
15
function &s()
16
{
17
    // т.к. эта функция вызывается очень часто - создадим статическую переменную
18
    static $_v;
19
20
    // Если переменная не определена - получим единственный экземпляр ядра
21
    if (!isset($_v)) {
22
        // Load instance from global snapshot
23
        if (isset($GLOBALS["__CORE_SNAPSHOT"])) {
24
            $_v = unserialize(base64_decode($GLOBALS["__CORE_SNAPSHOT"]));
25
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
26
        } else { // Create new instance
27
            $_v = new samson\core\Core();
28
        }
29
    }
30
31
    // Вернем указатель на ядро системы
32
    return $_v;
33
}
34
35
/**
36
 * Module(Модуль) - Получить Текущий модуль / Модуль по имени из стека модулей системы
37
 * @see        iCore::module();
38
 *
39
 * @param mixed $module Указатель на модуль системы *
40
 *
41
 * @return \samson\core\Module Текущую / Модель по её имени / или FALSE если модель не найдена
42
 * @deprecated Use $this->system->module() in module context
43
 */
44
function &m($module = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
45
{
46
    // т.к. эта функция вызывается очень часто - создадим статическую переменную
47
    static $_s;
48
49
    // Если переменная не определена - получим единственный экземпляр ядра
50
    if (!isset($_s)) $_s = &s();
0 ignored issues
show
Deprecated Code introduced by
The function s() has been deprecated with message: Use $this->system in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
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...
51
52
    // Вернем указатель на модуль системы
53
    return $_s->module($module);
54
}
55
56
/**
57
 * Error(Ошибка) - Зафиксировать ошибку работы системы
58
 *
59
 * @param string $error_msg  Текст ошибки
60
 * @param int    $error_code Код ошибки
61
 * @param mixed  $args       Специальные "жетоны" для вставки в текст ошибки
62
 * @param mixed  $ret_val    Value that must be returned by the function
63
 *
64
 * @return bool FALSE для остановки работы функции или условия
65
 * @throws Exception
66
 * @deprecated Use custom exceptions
67
 */
68
function e($error_msg = '', $error_code = E_USER_NOTICE, $args = NULL, & $ret_val = false)
0 ignored issues
show
Unused Code introduced by
The parameter $error_code is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $ret_val is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
69
{
70
    // Если передан только один аргумент то сделаем из него массив для совместимости
71
    $args = is_array($args) ? $args : array($args);
72
73
    // "Украсим" сообщение об ошибке используя переданные аргументы, если они есть
74
    if (isset($args)) {
75
        $error_msg = debug_parse_markers($error_msg, $args);
76
    }
77
78
    throw new \Exception($error_msg);
79
80
    return $ret_val;
0 ignored issues
show
Unused Code introduced by
return $ret_val; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
81
}
82
83
/**
84
 * Установить все доступные локализации для текущего веб-приложения.
85
 * Локализацию по умолчанию, передавать не нужно, т.к. она уже включена в список
86
 * и описана в <code>SamsonLocale::DEF</code>
87
 *
88
 * Достуные локализации передаются в функцию в виде обычных аргументов функции:
89
 * Для исключения ошибок рекомендуется передавать константы класса SamsonLocale
90
 * <code>setlocales( SamsonLocale::UA, SamsonLocale::EN )</code>
91
 *
92
 * @see SamsonLocale::set()
93
 */
94
function setlocales()
95
{
96
    $args = func_get_args();
97
    \samson\core\SamsonLocale::set($args);
98
}
99
100
/**
101
 * Установить/Получить текущую локализацию сайта
102
 *
103
 * @see SamsonLocale::current()
104
 *
105
 * @param string $locale Значение локали
106
 *
107
 * @return string Возвращает текущее значение локали сайта до момента вызова метода
108
 */
109
function locale($locale = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
110
{
111
    return \samson\core\SamsonLocale::current($locale);
112
}
113
114
/**
115
 * Check if passed locale alias matches current locale and output in success
116
 *
117
 * @param string $locale Locale alias to compare with current locale
118
 * @param string $output Output string on success
119
 *
120
 * @return boolean True if passed locale alias matches current locale
121
 */
122
function islocale($locale, $output = '')
123
{
124
    if (\samson\core\SamsonLocale::$current_locale == $locale) {
125
        echo $output;
126
        return true;
127
    }
128
    return false;
129
}
130
131
/**
132
 * Build string with locale to use in URL and file path
133
 *
134
 * @param string $l Locale name to use, if not passed - current locale is used
135
 *
136
 * @return string locale path if current locale is not default locale
137
 */
138
function locale_path($l = null)
139
{
140
    // If no locale is passed - get current locale
141
    $l = !isset($l) ? locale() : $l;
142
143
    // Build path starting with locale
144
    return ($l != \samson\core\SamsonLocale::DEF) ? $l . '/' : '';
145
}
146
147
/**
148
 * Build URL relative to current web-application, method accepts any number of arguments,
149
 * every argument starting from 2-nd firstly considered as module view parameter, if no such
150
 * parameters is found - its used as string.
151
 *
152
 * If current locale differs from default locale, current locale prepended to the beginning of URL
153
 *
154
 * @see URL::build()
155
 *
156
 * @return string Builded URL
157
 */
158
function url_build()
159
{
160
    // Get cached URL builder for speedup
161
    static $_v;
162
    $_v = isset($_v) ? $_v : url();
163
164
    // Get passed arguments
165
    $args = func_get_args();
166
167
    // If we have current locale set
168
    if (\samson\core\SamsonLocale::$leaveDefaultLocale && \samson\core\SamsonLocale::current() != \samson\core\SamsonLocale::DEF) {
169
        // Add locale as first url parameter
170
        array_unshift($args, \samson\core\SamsonLocale::current());
171
    }
172
173
    // Call URL builder with parameters
174
    return call_user_func_array(array($_v, 'build'), $args);
175
}
176
177
/**
178
 * Echo builded URL from passed parameters
179
 * @see url_build
180
 */
181
function url_base()
182
{
183
    $args = func_get_args();
184
185
    // Call URL builder and echo its result
186
    echo call_user_func_array('url_build', $args);
187
}
188
189
/**
190
 * Echo builded URL from passed parameters
191
 * @see url_build
192
 */
193
function url_hash()
194
{
195
    $args = func_get_args();
196
197
    // Call URL builder and echo its result
198
    $returnUrl = call_user_func_array('url_build', $args);
199
200
    // Return url with hash
201
    echo substr($returnUrl, 0, -1);
202
}
203
204
/**
205
 * Echo builded URL from passed parameters, prepending first parameter as current module identifier
206
 * @see url_build()
207
 */
208
function module_url()
209
{
210
    $args = func_get_args();
211
212
    echo call_user_func_array('url_build', array_merge(array(url()->module), $args));
213
}
214
215
216