empty_tag()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
if (! function_exists('html_implode')) {
3
    /**
4
     * Каждый элемент массива обернуть в html тег
5
     *
6
     * @param array $arr
7
     * @param string $el тег
8
     * @return string
9
     */
10
    function html_implode(array $arr, $el)
11
    {
12
        return "<$el>" . implode("</$el><$el>", $arr) . "</$el>";
13
    }
14
}
15
16
if (! function_exists('html_table')) {
17
    /**
18
     * Создать таблицу из массива
19
     *
20
     * @param array $rows массив строк таблицы (с тегами td)
21
     * @param array|string $table шапка таблицы
22
     * @param array $attr аттрибуты которые необходимо добавить к основному тегу table
23
     * @return string
24
     */
25
    function html_table($rows, $table = '', array $attr = [])
26
    {
27
        if (isset($table['head'])) {
28
            $thead = $table['head'];
29
        } elseif (is_array($table)) {
30
            $thead = html_implode($table, 'th');
31
        } else {
32
            $thead = $table;
33
        }
34
        if (! empty($thead)) {
35
            $thead = html_wrap('thead', html_wrap('tr', $thead));
36
        }
37
38
        return html_wrap(
39
            'table',
40
            $thead . html_wrap('tbody', (is_array($rows) ? html_implode($rows, 'tr') : $rows)),
0 ignored issues
show
introduced by
The condition is_array($rows) is always true.
Loading history...
41
            $attr
42
        );
43
    }
44
}
45
46
if (! function_exists('html_wrap')) {
47
    /**
48
     * Обернуть некий текст в html тег
49
     *
50
     * @param string $tag имя тега
51
     * @param string $content содержимое тега
52
     * @param array $attr аттрибуты которые необходимод обавить к тегу $tag
53
     * @return string
54
     */
55
    function html_wrap($tag, $content, $attr = [])
56
    {
57
        $attribs = html_attrs($attr);
58
59
        return "<{$tag}{$attribs}>{$content}</{$tag}>";
60
    }
61
}
62
63
if (! function_exists('empty_tag')) {
64
    /**
65
     * Создать пустой html тег
66
     *
67
     * @param string $tag имя тега
68
     * @param array $attr аттрибуты которые необходимод обавить к тегу $tag
69
     * @return string
70
     */
71
    function empty_tag($tag, $attr = [])
72
    {
73
        $attribs = html_attrs($attr);
74
75
        return "<{$tag}{$attribs}/>";
76
    }
77
}
78
79
if (! function_exists('html_attrs')) {
80
    /**
81
     * Создать список аттрибутов для html тега
82
     *
83
     * @param array $attr ассоциативный массив со списком аттрибутов
84
     * @param array $noEscape имена аттрибутов, значения которых не следует экранировать
85
     * @return string
86
     */
87
    function html_attrs($attr, $noEscape = ['href', 'src'])
88
    {
89
        $html = '';
90
        if (is_array($attr)) {
0 ignored issues
show
introduced by
The condition is_array($attr) is always true.
Loading history...
91
            foreach ($attr as $key => $val) {
92
                switch (true) {
93
                    case (is_scalar($val) && is_scalar($key)):
94
                        $html .= ' ' . $key . '="' . (in_array($key, $noEscape) ? $val : e($val)) . '"';
95
                        break;
96
                    case ($val === true && is_scalar($key)):
97
                        $html .= ' ' . $key;
98
                        break;
99
                }
100
            }
101
        }
102
103
        return $html;
104
    }
105
}
106
107
if (! function_exists('make_options')) {
108
    /**
109
     * Создать html список select для формы
110
     *
111
     * @param string $name имя select формы
112
     * @param array $data многомерный ассоциативный массив с возможными значениями. Ключи массива - текст для возможного значения, а содержимое - аттрибуты
113
     * @param null $current текущее значение которое должно быть отмечено как активное
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $current is correct as it would always require null to be passed?
Loading history...
114
     * @param null $default значение по умолчанию (если текущее значение отсутствует в возможных значениях или вообще не определено)
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
115
     * @param array $main_attr аттрибуты для основного html тега select
116
     * @return string
117
     */
118
    function make_options($name, $data = [], $current = null, $default = null, $main_attr = [])
119
    {
120
        $out = '';
121
        $options = [];
122
        $selected = false;
123
        foreach ($data as $title => $value) {
124
            if (! is_array($value)) {
125
                $value = [
126
                    'value' => $value
127
                ];
128
            }
129
            $val = get_key($value, 'value', '');
130
            if (is_int($title)) {
131
                $title = get_key($value, 'value', $title);
132
            }
133
            if ((string)$val === (string)$current) {
134
                $value['selected'] = true;
135
                $selected = true;
136
            } else {
137
                unset($value['selected']);
138
            }
139
140
            $options[$title] = $value;
141
        }
142
        foreach ($options as $title => $attr) {
143
            if (! $selected && get_key($attr, 'value', '') == $default) {
144
                $attr['selected'] = true;
145
            }
146
            $out .= html_wrap('option', $title, $attr);
147
        }
148
        $main_attr['name'] = $name;
149
150
        return html_wrap('select', $out, $main_attr);
151
    }
152
}
153
154
if (! function_exists('img_tag')) {
155
    /**
156
     * Создать html тег img
157
     *
158
     * @param string $src путь к картинке
159
     * @param array $attr массив аттрибутов для тега img
160
     * @return string
161
     */
162
    function img_tag($src, $attr = [])
163
    {
164
        $attr['src'] = $src;
165
166
        return empty_tag('img', $attr);
167
    }
168
}
169
170
if (! function_exists('a_tag')) {
171
    /**
172
     * Создать html тег a
173
     *
174
     * @param string $url ссылка
175
     * @param string $text текст ссылки
176
     * @param array $options массив аттрибутов для тега a
177
     * @return string
178
     */
179
    function a_tag($url, $text, $options = [])
180
    {
181
        $options['href'] = $url;
182
        $options['title'] = strip_tags(get_key($options, 'title', $text));
183
184
        return html_wrap('a', $text, $options);
185
    }
186
}
187
188
if (! function_exists('input_tag')) {
189
    /**
190
     * Создать html тег input
191
     *
192
     * @param string $name имя input тега
193
     * @param string $value значение тега
194
     * @param string $type тип input тега
195
     * @param array $options дополнительные аттрибуты тега
196
     * @return string
197
     */
198
    function input_tag($name, $value = '', $type = 'text', $options = [])
199
    {
200
        return empty_tag('input', array_merge($options, [
201
            'type'  => $type,
202
            'name'  => $name,
203
            'value' => $value
204
        ]));
205
    }
206
}
207
208
if (! function_exists('stylesheet_link_tag')) {
209
    /**
210
     * Создать html тег для подключения файла с CSS стилями
211
     *
212
     * @param string $css путь к файлу со стилями
213
     * @param array $options дополнительный массив аттрибутов тега link
214
     * @return string
215
     */
216
    function stylesheet_link_tag($css, $options = [])
217
    {
218
        $options['href'] = $css;
219
        $options['rel'] = 'stylesheet';
220
        $options['type'] = 'text/css';
221
222
        return empty_tag('link', $options);
223
    }
224
}
225
226
if (! function_exists('javascript_include_tag')) {
227
    /**
228
     * Создать html тег для подключения файла с JavaScript
229
     *
230
     * @param string $js путь к файлу
231
     * @param array $options массив аттрибутов тега script
232
     * @return string
233
     */
234
    function javascript_include_tag($js, $options = [])
235
    {
236
        $options['src'] = $js;
237
        $options['type'] = 'text/javascript';
238
239
        return html_wrap('script', '', $options);
240
    }
241
}
242
243
if (! function_exists('between_tag')) {
244
    /**
245
     * Вырезание текста между HTML тэгов
246
     *
247
     * @param string $html HTML текст
248
     * @param string $tag HTML тэг в котором производить поиск
249
     * @return array
250
     */
251
    function between_tag($html, $tag = 'pre')
252
    {
253
        $replace = $count = [];
254
        $j = 0;
255
        do {
256
            $new = false;
257
            //Поиск открывающего тэга (одного!)
258
            preg_match('%(<' . $tag . '[^>]*>)(.*)%s', $html, $m);
259
260
            if (isset($m[1], $m[2])) {
261
                //Начинаем поиски закрывающих тегов (всех до конца документа)
262
                preg_match_all('%</' . $tag . '[^>]*>%is', $m[2], $tmp, PREG_OFFSET_CAPTURE);
263
                if (! empty($tmp[0])) {
264
                    foreach ($tmp[0] as $j => $subTmp) {
265
                        $closeTag = $subTmp[0]; //закрывающий тэг
266
                        $subText = substr($m[2], 0, $subTmp[1]); //Тексту внутри тэгов
267
268
                        //подсчет открывающих тэгов внутри полученного текста
269
                        preg_match_all('%(<' . $tag . '[^>]*>)%s', $subText, $count);
270
                        if (count($count[0]) == $j) {
271
                            $replace[] = [$m[1], $subText, $closeTag];
272
                            $new = true;
273
                            break;
274
                        }
275
                    }
276
                    $html = substr($m[2], $tmp[0][$j][1] + strlen($tmp[0][$j][0]));
277
                }
278
                if (! $new) {
279
                    if (isset($tmp[0][$j]) && $j < $count[0]) {
280
                        $subTmp = $tmp[0][$j];
281
                        $closeTag = $subTmp[0];
282
283
                        $subText = substr($m[2], 0, $subTmp[1]) . $closeTag;
284
                        $html = substr($m[2], $subTmp[1] + strlen($closeTag));
285
                        $replace[] = [$m[1], $subText, $closeTag];
286
                    } else {
287
                        $replace[] = [$m[1], $m[2], ''];
288
                        $html = '';
289
                    }
290
                }
291
            } else {
292
                $html = '';
293
            }
294
        } while (! empty($html));
295
296
        return $replace;
297
    }
298
}
299
300
if (! function_exists('clear_html')) {
301
    /**
302
     * Удаление комментариев, переносов и лишних пробелов из html строки
303
     *
304
     * @param string $html HTML текст
305
     * @return string
306
     */
307
    function clear_html($html)
308
    {
309
        $filters = [
310
            '/<!--([^\[|(<!)].*)-->/i' => '', // Remove HTML Comments (breaks with HTML5 Boilerplate)
311
            '/(?<!\S)\/\/\s*[^\r\n]*/' => '', // Remove comments in the form /* */
312
            '/\s{2,}/'                 => ' ', // Shorten multiple white spaces
313
            '/(\r?\n)/'                => '', // Collapse new lines
314
        ];
315
316
        return is_scalar($html) ? preg_replace(array_keys($filters), array_values($filters), $html) : '';
0 ignored issues
show
introduced by
The condition is_scalar($html) is always true.
Loading history...
317
    }
318
}
319