1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Utils;
9:
10: use Nette;
11:
12:
13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23:
24: class Html implements \ArrayAccess, \Countable, \IteratorAggregate, IHtmlString
25: {
26: use Nette\SmartObject;
27:
28:
29: public $attrs = [];
30:
31:
32: public static $xhtml = false;
33:
34:
35: public static $emptyElements = [
36: 'img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1,
37: 'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1,
38: 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1,
39: ];
40:
41:
42: protected $children = [];
43:
44:
45: private $name;
46:
47:
48: private $isEmpty;
49:
50:
51: 52: 53: 54: 55: 56:
57: public static function el($name = null, $attrs = null)
58: {
59: $el = new static;
60: $parts = explode(' ', (string) $name, 2);
61: $el->setName($parts[0]);
62:
63: if (is_array($attrs)) {
64: $el->attrs = $attrs;
65:
66: } elseif ($attrs !== null) {
67: $el->setText($attrs);
68: }
69:
70: if (isset($parts[1])) {
71: foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i') as $m) {
72: $el->attrs[$m[1]] = isset($m[3]) ? $m[3] : true;
73: }
74: }
75:
76: return $el;
77: }
78:
79:
80: 81: 82: 83: 84: 85: 86:
87: public function setName($name, $isEmpty = null)
88: {
89: if ($name !== null && !is_string($name)) {
90: throw new Nette\InvalidArgumentException(sprintf('Name must be string or null, %s given.', gettype($name)));
91: }
92:
93: $this->name = $name;
94: $this->isEmpty = $isEmpty === null ? isset(static::$emptyElements[$name]) : (bool) $isEmpty;
95: return $this;
96: }
97:
98:
99: 100: 101: 102:
103: public function getName()
104: {
105: return $this->name;
106: }
107:
108:
109: 110: 111: 112:
113: public function isEmpty()
114: {
115: return $this->isEmpty;
116: }
117:
118:
119: 120: 121: 122: 123:
124: public function addAttributes(array $attrs)
125: {
126: $this->attrs = array_merge($this->attrs, $attrs);
127: return $this;
128: }
129:
130:
131: 132: 133: 134: 135: 136: 137:
138: public function appendAttribute($name, $value, $option = true)
139: {
140: if (is_array($value)) {
141: $prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : [];
142: $this->attrs[$name] = $value + $prev;
143:
144: } elseif ((string) $value === '') {
145: $tmp = &$this->attrs[$name];
146:
147: } elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) {
148: $this->attrs[$name][$value] = $option;
149:
150: } else {
151: $this->attrs[$name] = [$this->attrs[$name] => true, $value => $option];
152: }
153: return $this;
154: }
155:
156:
157: 158: 159: 160: 161: 162:
163: public function setAttribute($name, $value)
164: {
165: $this->attrs[$name] = $value;
166: return $this;
167: }
168:
169:
170: 171: 172: 173: 174:
175: public function getAttribute($name)
176: {
177: return isset($this->attrs[$name]) ? $this->attrs[$name] : null;
178: }
179:
180:
181: 182: 183: 184: 185:
186: public function removeAttribute($name)
187: {
188: unset($this->attrs[$name]);
189: return $this;
190: }
191:
192:
193: 194: 195: 196: 197: 198:
199: public function __set($name, $value)
200: {
201: $this->attrs[$name] = $value;
202: }
203:
204:
205: 206: 207: 208: 209:
210: public function &__get($name)
211: {
212: return $this->attrs[$name];
213: }
214:
215:
216: 217: 218: 219: 220:
221: public function __isset($name)
222: {
223: return isset($this->attrs[$name]);
224: }
225:
226:
227: 228: 229: 230: 231:
232: public function __unset($name)
233: {
234: unset($this->attrs[$name]);
235: }
236:
237:
238: 239: 240: 241: 242: 243:
244: public function __call($m, $args)
245: {
246: $p = substr($m, 0, 3);
247: if ($p === 'get' || $p === 'set' || $p === 'add') {
248: $m = substr($m, 3);
249: $m[0] = $m[0] | "\x20";
250: if ($p === 'get') {
251: return isset($this->attrs[$m]) ? $this->attrs[$m] : null;
252:
253: } elseif ($p === 'add') {
254: $args[] = true;
255: }
256: }
257:
258: if (count($args) === 0) {
259:
260: } elseif (count($args) === 1) {
261: $this->attrs[$m] = $args[0];
262:
263: } else {
264: $this->appendAttribute($m, $args[0], $args[1]);
265: }
266:
267: return $this;
268: }
269:
270:
271: 272: 273: 274: 275: 276:
277: public function href($path, $query = null)
278: {
279: if ($query) {
280: $query = http_build_query($query, '', '&');
281: if ($query !== '') {
282: $path .= '?' . $query;
283: }
284: }
285: $this->attrs['href'] = $path;
286: return $this;
287: }
288:
289:
290: 291: 292: 293:
294: public function data($name, $value = null)
295: {
296: if (func_num_args() === 1) {
297: $this->attrs['data'] = $name;
298: } else {
299: $this->attrs["data-$name"] = is_bool($value) ? json_encode($value) : $value;
300: }
301: return $this;
302: }
303:
304:
305: 306: 307: 308: 309: 310:
311: public function setHtml($html)
312: {
313: if (is_array($html)) {
314: throw new Nette\InvalidArgumentException(sprintf('Textual content must be a scalar, %s given.', gettype($html)));
315: }
316: $this->removeChildren();
317: $this->children[] = (string) $html;
318: return $this;
319: }
320:
321:
322: 323: 324: 325:
326: public function getHtml()
327: {
328: return implode('', $this->children);
329: }
330:
331:
332: 333: 334: 335: 336: 337:
338: public function setText($text)
339: {
340: if (!$text instanceof IHtmlString) {
341: $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8');
342: }
343: return $this->setHtml($text);
344: }
345:
346:
347: 348: 349: 350:
351: public function getText()
352: {
353: return html_entity_decode(strip_tags($this->getHtml()), ENT_QUOTES, 'UTF-8');
354: }
355:
356:
357: 358: 359:
360: public function add($child)
361: {
362: trigger_error(__METHOD__ . '() is deprecated, use addHtml() or addText() instead.', E_USER_DEPRECATED);
363: return $this->addHtml($child);
364: }
365:
366:
367: 368: 369: 370: 371:
372: public function addHtml($child)
373: {
374: return $this->insert(null, $child);
375: }
376:
377:
378: 379: 380: 381: 382:
383: public function addText($text)
384: {
385: if (!$text instanceof IHtmlString) {
386: $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8');
387: }
388: return $this->insert(null, $text);
389: }
390:
391:
392: 393: 394: 395: 396: 397:
398: public function create($name, $attrs = null)
399: {
400: $this->insert(null, $child = static::el($name, $attrs));
401: return $child;
402: }
403:
404:
405: 406: 407: 408: 409: 410: 411: 412:
413: public function insert($index, $child, $replace = false)
414: {
415: if ($child instanceof IHtmlString || is_scalar($child)) {
416: $child = $child instanceof self ? $child : (string) $child;
417: if ($index === null) {
418: $this->children[] = $child;
419:
420: } else {
421: array_splice($this->children, (int) $index, $replace ? 1 : 0, [$child]);
422: }
423:
424: } else {
425: throw new Nette\InvalidArgumentException(sprintf('Child node must be scalar or Html object, %s given.', is_object($child) ? get_class($child) : gettype($child)));
426: }
427:
428: return $this;
429: }
430:
431:
432: 433: 434: 435: 436: 437:
438: public function offsetSet($index, $child)
439: {
440: $this->insert($index, $child, true);
441: }
442:
443:
444: 445: 446: 447: 448:
449: public function offsetGet($index)
450: {
451: return $this->children[$index];
452: }
453:
454:
455: 456: 457: 458: 459:
460: public function offsetExists($index)
461: {
462: return isset($this->children[$index]);
463: }
464:
465:
466: 467: 468: 469: 470:
471: public function offsetUnset($index)
472: {
473: if (isset($this->children[$index])) {
474: array_splice($this->children, (int) $index, 1);
475: }
476: }
477:
478:
479: 480: 481: 482:
483: public function count()
484: {
485: return count($this->children);
486: }
487:
488:
489: 490: 491: 492:
493: public function removeChildren()
494: {
495: $this->children = [];
496: }
497:
498:
499: 500: 501: 502:
503: public function getIterator()
504: {
505: return new \ArrayIterator($this->children);
506: }
507:
508:
509: 510: 511: 512:
513: public function getChildren()
514: {
515: return $this->children;
516: }
517:
518:
519: 520: 521: 522: 523:
524: public function render($indent = null)
525: {
526: $s = $this->startTag();
527:
528: if (!$this->isEmpty) {
529:
530: if ($indent !== null) {
531: $indent++;
532: }
533: foreach ($this->children as $child) {
534: if (is_object($child)) {
535: $s .= $child->render($indent);
536: } else {
537: $s .= $child;
538: }
539: }
540:
541:
542: $s .= $this->endTag();
543: }
544:
545: if ($indent !== null) {
546: return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2));
547: }
548: return $s;
549: }
550:
551:
552: public function __toString()
553: {
554: try {
555: return $this->render();
556: } catch (\Exception $e) {
557: } catch (\Throwable $e) {
558: }
559: trigger_error('Exception in ' . __METHOD__ . "(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", E_USER_ERROR);
560: }
561:
562:
563: 564: 565: 566:
567: public function startTag()
568: {
569: if ($this->name) {
570: return '<' . $this->name . $this->attributes() . (static::$xhtml && $this->isEmpty ? ' />' : '>');
571:
572: } else {
573: return '';
574: }
575: }
576:
577:
578: 579: 580: 581:
582: public function endTag()
583: {
584: return $this->name && !$this->isEmpty ? '</' . $this->name . '>' : '';
585: }
586:
587:
588: 589: 590: 591: 592:
593: public function attributes()
594: {
595: if (!is_array($this->attrs)) {
596: return '';
597: }
598:
599: $s = '';
600: $attrs = $this->attrs;
601: if (isset($attrs['data']) && is_array($attrs['data'])) {
602: trigger_error('Expanded attribute "data" is deprecated.', E_USER_DEPRECATED);
603: foreach ($attrs['data'] as $key => $value) {
604: $attrs['data-' . $key] = $value;
605: }
606: unset($attrs['data']);
607: }
608:
609: foreach ($attrs as $key => $value) {
610: if ($value === null || $value === false) {
611: continue;
612:
613: } elseif ($value === true) {
614: if (static::$xhtml) {
615: $s .= ' ' . $key . '="' . $key . '"';
616: } else {
617: $s .= ' ' . $key;
618: }
619: continue;
620:
621: } elseif (is_array($value)) {
622: if (strncmp($key, 'data-', 5) === 0) {
623: $value = Json::encode($value);
624:
625: } else {
626: $tmp = null;
627: foreach ($value as $k => $v) {
628: if ($v != null) {
629:
630: $tmp[] = $v === true ? $k : (is_string($k) ? $k . ':' . $v : $v);
631: }
632: }
633: if ($tmp === null) {
634: continue;
635: }
636:
637: $value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp);
638: }
639:
640: } elseif (is_float($value)) {
641: $value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');
642:
643: } else {
644: $value = (string) $value;
645: }
646:
647: $q = strpos($value, '"') === false ? '"' : "'";
648: $s .= ' ' . $key . '=' . $q
649: . str_replace(
650: ['&', $q, '<'],
651: ['&', $q === '"' ? '"' : ''', self::$xhtml ? '<' : '<'],
652: $value
653: )
654: . (strpos($value, '`') !== false && strpbrk($value, ' <>"\'') === false ? ' ' : '')
655: . $q;
656: }
657:
658: $s = str_replace('@', '@', $s);
659: return $s;
660: }
661:
662:
663: 664: 665:
666: public function __clone()
667: {
668: foreach ($this->children as $key => $value) {
669: if (is_object($value)) {
670: $this->children[$key] = clone $value;
671: }
672: }
673: }
674: }
675: