View.php ➔ isval()   B
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 6
nop 5
dl 0
loc 18
ccs 0
cts 6
cp 0
crap 30
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>
4
 * on 24.04.14 at 18:01
5
 */
6
7
/**
8
 * View variable( Переменная представления ) - Вывести значение переменной представления
9
 * текущего модуля системы в текущий поток вывода.
10
 *
11
 * @see iModule
12
 * @see iCore::active()
13
 *
14
 * Это дает возможность использовать функцию в представлениях для более компактной записи:
15
 * <code><?php v('MODULE_VAR')?></code>
16
 *
17
 * Для возравщения значения переменной, без её вывода в поток, необходимо использовать
18
 *    Для переменный представления:
19
 *        m( MODEL_NAME )->set( VAR_NAME ) либо $VIEW_VAR_NAME
20
 *    Для переменных модуля:
21
 *        m( MODEL_NAME )->VAR_NAME;
22
 *
23
 * @param string $name Имя переменной представления текущего модуля
24
 * @param null   $realName
25
 */
26
function v($name, $realName = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
27
{
28
    // Получим указатель на текущий модуль
29
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
30
31
    // Если передана ПРАВДА - используем первый параметр как имя
32
    if (is_bool($realName) && ($realName === true)) $realName = '__dm__' . $name;
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...
33
    else $realName = '__dm__' . $realName;
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...
34
35
    // Если задано специальное значение - выведем его
36
    if (isset($realName) && $m->offsetExists($realName)) echo $m[$realName];
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...
37
    // Если дополнительный параметр не задан и у текущего модуля задана требуемое
38
    // поле - выведем его значение в текущий поток вывода
39
    else if ($m->offsetExists($name)) echo $m[$name];
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...
40
    // Otherwise just output
41
    else echo $name;
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...
42
}
43
44
/**
45
 * IV(If view variable) - output view variable only if is correctly set for view output *
46
 */
47
function iv($name, $realName = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $realName 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...
48
{
49
    // Cache current module pointer
50
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
51
52
    // If view variable is set - echo it
53
    if (isvalue($m, $name)) echo $m[$name];
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...
Bug introduced by
It seems like $m defined by m() on line 50 can be null; however, isvalue() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
54
}
55
56
/**
57
 * View variable for Input( Переменная представления ) - Вывести значение переменной представления
58
 * текущего модуля системы в текущий поток вывода c декодирования HTML символов.
59
 *
60
 * Используется для HTML полей ввода
61
 *
62
 * @see v()
63
 *
64
 * @param string $name Имя переменной представления текущего модуля
65
 */
66
function vi($name)
67
{
68
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
69
    if ($m->offsetExists($name)) echo htmlentities($m[$name], ENT_QUOTES, 'UTF-8');
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...
70
}
71
72
/**
73
 * Figure out if module view variable value is correctly set for view output
74
 *
75
 * @param \samson\core\iModule $m     Pointer to module
76
 * @param string               $name  View variable name
77
 * @param mixed                $value Value to compare
78
 *
79
 * @return boolean If view variable can be displayed in view
80
 */
81
function isvalue($m, $name, $value = null)
82
{
83
    // If we have module view variable
84
    if (isset($m[$name])) {
85
        // Get value
86
        $var = $m[$name];
87
88
        //trace($name.'-'.$var.'-'.gettype( $var ).'-'.$value);
89
90
        // Get variable type
91
        switch (gettype($var)) {
92
            // If this is boolean and it matches $value
93
            case 'boolean':
94
                return (isset($value) ? $var == $value : $var);
95
            // If this is number and it matches $value
96
            case 'integer':
97
                return (isset($value) ? $var === intval($value) : $var);
98
            // If this is double and it matches $value
99
            case 'double':
100
                return (isset($value) ? $var === doubleval($value) : $var);
101
            // If this is double and it matches $value
102
            case 'float':
103
                return (isset($value) ? $var === floatval($value) : $var);
104
            // If this is not empty array
105
            case 'array':
106
                return sizeof($var);
107
            // If this is a string and it matches $value or if no $value is set string is not empty
108
            case 'string':
109
                return (!isset($value) && isset($var{0})) ||
110
                (isset($value) && $var === strval($value));
111
            // If this is an object consider it as ok
112
            case 'object':
113
                return true;
114
            // Not supported for now
115
            case 'NULL':
116
            case 'unknown type':
117
            default:
118
                return false;
119
        }
120
    }
121
}
122
123
/**
124
 * Is Value( Является ли значением) - Проверить является ли переменная представления
125
 * указанным значением. Метод проверяет тип переменной и в зависимости от этого проверяет
126
 * соответствует ли переменная представления заданному значению:
127
 *  - проверяется задана ли переменная вообще
128
 *  - если передана строка то проверяется соответствует ли она заданному значению
129
 *  - если передано число то проверяется равно ли оно заданому значению
130
 *
131
 * Все сравнения происходят при преобразовании входного значения в тип переменной
132
 * представления.
133
 *
134
 * По умолчанию выполняется сравнение значения переменной представления
135
 * с символом '0'. Т.к. это самый частый вариант использования когда необходимо получить значение
136
 * переменной объекта полученного из БД, у которого все поля это строки, за исключением
137
 * собственно описанных полей.
138
 *
139
 * @param string  $name    Module view variable name
140
 * @param mixed   $value   Value for checking
141
 * @param string  $success Value for outputting in case of success
142
 * @param string  $failure Value for outputting in case of failure
143
 * @param boolean $inverse Value for outputting in case of success
144
 *
145
 * @return boolean Соответствует ли указанная переменная представления переданному значению
146
 */
147
function isval($name, $value = null, $success = null, $failure = null, $inverse = false)
148
{
149
    // Pointer to current module
150
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
151
152
    // Flag for checking module value
153
    $ok = isvalue($m, $name, $value);
0 ignored issues
show
Bug introduced by
It seems like $m defined by m() on line 150 can be null; however, isvalue() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
154
155
    // If inversion is on
156
    if ($inverse) $ok = !$ok;
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...
157
158
    // If we have success value - output it
159
    if ($ok && isset($success)) v($success);
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...
160
    // If we have failure value - output it
161
    else if (isset($failure)) v($failure);
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...
162
163
    return $ok;
164
}
165
166
/**
167
 * Is Variable exists, also checks:
168
 *  - if module view variable is not empty array
169
 *  - if module view variable is not empty string
170
 *
171
 * @param string $name    Имя переменной для проверки
172
 * @param string $success Value for outputting in case of success
173
 * @param string $failure Value for outputting in case of failure
174
 *
175
 * @return boolean True if variable exists
176
 */
177
function isv($name, $success = null, $failure = null)
178
{
179
    return isval($name, null, $success, $failure);
180
}
181
182
/**
183
 * Is Variable DOES NOT exists, also checks:
184
 *  - if module view variable is empty array
185
 *  - if module view variable is empty string
186
 *
187
 * @param string $name    Имя переменной для проверки
188
 * @param string $success Value for outputting in case of success
189
 * @param string $failure Value for outputting in case of failure
190
 *
191
 * @return boolean True if variable exists
192
 */
193
function isnv($name, $success = null, $failure = null)
194
{
195
    return isval($name, null, $success, $failure, true);
196
}
197
198
/**
199
 * Is NOT value - checks if module view variable value does not match $value
200
 *
201
 * @param string $name    Module view variable name
202
 * @param mixed  $value   Value for checking
203
 * @param string $success Value for outputting in case of success
204
 * @param string $failure Value for outputting in case of failure
205
 *
206
 * @return boolean True if value does NOT match
207
 */
208
function isnval($name, $value = null, $success = null, $failure = null)
209
{
210
    return isval($name, $value, $success, $failure, true);
211
}
212
213
/**
214
 * Echo HTML link tag with text value from module view variable
215
 *
216
 * @param string $name  View variable name
217
 * @param string $href  Link url
218
 * @param string $class CSS class
219
 * @param string $id    HTML identifier
220
 * @param string $title Title tag value
221
 */
222
function vhref($name, $href = null, $class = null, $id = null, $title = null)
223
{
224
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
225
226
    // If value can be displayed
227
    if (isvalue($m, $name) || isvalue($m, $href)) {
0 ignored issues
show
Bug introduced by
It seems like $m defined by m() on line 224 can be null; however, isvalue() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
228
        $name = isset($m[$name]) ? $m[$name] : $name;
229
230
        $href = isset($m[$href]) ? $m[$href] : $href;
231
232
        echo '<a id="' . $id . '" class="' . $class . '" href="' . $href . '" title="' . $title . '" >' . $name . '</a>';
233
    }
234
}
235
236
/**
237
 * Render IMG html tag
238
 *
239
 * @param string $src   Module view variable name to parse and get path to image
240
 * @param string $id    Image identifier
241
 * @param string $class Image CSS class
242
 * @param string $alt   Image alt text
243
 * @param string $dummy Dummy image path not set *
244
 */
245
function vimg($src, $id = '', $class = '', $alt = '', $dummy = null)
246
{
247
    // Закешируем ссылку на текущий модуль
248
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
249
250
    // Проверим задана ли указанная переменная представления в текущем модуле
251
    if ($m->offsetExists($src)) $src = $m[$src];
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...
252
    //
253
    elseif (isset($dummy)) $src = $dummy;
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...
254
255
    // We always build path to images fully independant of web-application or module relatively to base web-app
256
    //if( $src{0} != '/' ) $src = '/'.$src;
257
258
    // Выведем изображение
259
    echo '<img src="' . $src . '" id="' . $id . '" class="' . $class . '" alt="' . $alt . '" title="' . $alt . '">';
260
}
261
262
/**
263
 * Output view variable as date with formating
264
 * If view variable exists then output it as date with formatting
265
 *
266
 * @param string $name     Module view variable name
267
 * @param string $format   Date format string
268
 * @param string $function Function callback to render date
269
 */
270
function vdate($name, $format = 'h:i d.m.y', $function = 'date')
271
{
272
    // Cache current module
273
    $m = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
274
275
    // If view variable is set - echo with format
276
    if ($m->offsetExists($name)) echo $function($format, strtotime($m[$name]));
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...
277
278
}
279
280
/**
281
 * Is Module ( Является ли текущий модуль указанным ) - Проверить совпадает ли имя текущего модуля с указанным
282
 *
283
 * @param string $name Имя требуемого модуля для сравнения с текущим
284
 *
285
 * @return boolean Является ли имя текущего модуля равным переданному
286
 */
287
function ism($name)
288
{
289
    return (m()->id() == $name);
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() 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...
290
}
291