Completed
Push — master ( 8a7d45...7daebe )
by Agel_Nash
02:55
created

html.functions.php ➔ make_options()   C

Complexity

Conditions 8
Paths 27

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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