Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • ArrayHash
  • ArrayList
  • Arrays
  • Callback
  • DateTime
  • FileSystem
  • Finder
  • Html
  • Image
  • Json
  • LimitedScope
  • MimeTypeDetector
  • ObjectMixin
  • Paginator
  • Random
  • Strings
  • TokenIterator
  • Tokenizer
  • Validators

Interfaces

  • IHtmlString

Exceptions

  • AssertionException
  • ImageException
  • JsonException
  • RegexpException
  • TokenizerException
  • UnknownImageFileException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Utils;
  9: 
 10: use Nette;
 11: 
 12: 
 13: /**
 14:  * HTML helper.
 15:  *
 16:  * <code>
 17:  * $el = Html::el('a')->href($link)->setText('Nette');
 18:  * $el->class = 'myclass';
 19:  * echo $el;
 20:  *
 21:  * echo $el->startTag(), $el->endTag();
 22:  * </code>
 23:  */
 24: class Html extends Nette\Object implements \ArrayAccess, \Countable, \IteratorAggregate, IHtmlString
 25: {
 26:     /** @var string  element's name */
 27:     private $name;
 28: 
 29:     /** @var bool  is element empty? */
 30:     private $isEmpty;
 31: 
 32:     /** @var array  element's attributes */
 33:     public $attrs = array();
 34: 
 35:     /** @var array  of Html | string nodes */
 36:     protected $children = array();
 37: 
 38:     /** @var bool  use XHTML syntax? */
 39:     public static $xhtml = FALSE;
 40: 
 41:     /** @var array  empty (void) elements */
 42:     public static $emptyElements = array(
 43:         'img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1,
 44:         'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1,
 45:         'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1,
 46:     );
 47: 
 48: 
 49:     /**
 50:      * Static factory.
 51:      * @param  string element name (or NULL)
 52:      * @param  array|string element's attributes or plain text content
 53:      * @return self
 54:      */
 55:     public static function el($name = NULL, $attrs = NULL)
 56:     {
 57:         $el = new static;
 58:         $parts = explode(' ', $name, 2);
 59:         $el->setName($parts[0]);
 60: 
 61:         if (is_array($attrs)) {
 62:             $el->attrs = $attrs;
 63: 
 64:         } elseif ($attrs !== NULL) {
 65:             $el->setText($attrs);
 66:         }
 67: 
 68:         if (isset($parts[1])) {
 69:             foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i') as $m) {
 70:                 $el->attrs[$m[1]] = isset($m[3]) ? $m[3] : TRUE;
 71:             }
 72:         }
 73: 
 74:         return $el;
 75:     }
 76: 
 77: 
 78:     /**
 79:      * Changes element's name.
 80:      * @param  string
 81:      * @param  bool  Is element empty?
 82:      * @return self
 83:      * @throws Nette\InvalidArgumentException
 84:      */
 85:     public function setName($name, $isEmpty = NULL)
 86:     {
 87:         if ($name !== NULL && !is_string($name)) {
 88:             throw new Nette\InvalidArgumentException(sprintf('Name must be string or NULL, %s given.', gettype($name)));
 89:         }
 90: 
 91:         $this->name = $name;
 92:         $this->isEmpty = $isEmpty === NULL ? isset(static::$emptyElements[$name]) : (bool) $isEmpty;
 93:         return $this;
 94:     }
 95: 
 96: 
 97:     /**
 98:      * Returns element's name.
 99:      * @return string
100:      */
101:     public function getName()
102:     {
103:         return $this->name;
104:     }
105: 
106: 
107:     /**
108:      * Is element empty?
109:      * @return bool
110:      */
111:     public function isEmpty()
112:     {
113:         return $this->isEmpty;
114:     }
115: 
116: 
117:     /**
118:      * Sets multiple attributes.
119:      * @param  array
120:      * @return self
121:      */
122:     public function addAttributes(array $attrs)
123:     {
124:         $this->attrs = array_merge($this->attrs, $attrs);
125:         return $this;
126:     }
127: 
128: 
129:     /**
130:      * Overloaded setter for element's attribute.
131:      * @param  string    HTML attribute name
132:      * @param  mixed     HTML attribute value
133:      * @return void
134:      */
135:     public function __set($name, $value)
136:     {
137:         $this->attrs[$name] = $value;
138:     }
139: 
140: 
141:     /**
142:      * Overloaded getter for element's attribute.
143:      * @param  string    HTML attribute name
144:      * @return mixed     HTML attribute value
145:      */
146:     public function &__get($name)
147:     {
148:         return $this->attrs[$name];
149:     }
150: 
151: 
152:     /**
153:      * Overloaded tester for element's attribute.
154:      * @param  string    HTML attribute name
155:      * @return bool
156:      */
157:     public function __isset($name)
158:     {
159:         return isset($this->attrs[$name]);
160:     }
161: 
162: 
163:     /**
164:      * Overloaded unsetter for element's attribute.
165:      * @param  string    HTML attribute name
166:      * @return void
167:      */
168:     public function __unset($name)
169:     {
170:         unset($this->attrs[$name]);
171:     }
172: 
173: 
174:     /**
175:      * Overloaded setter for element's attribute.
176:      * @param  string  HTML attribute name
177:      * @param  array   (string) HTML attribute value or pair?
178:      * @return self
179:      */
180:     public function __call($m, $args)
181:     {
182:         $p = substr($m, 0, 3);
183:         if ($p === 'get' || $p === 'set' || $p === 'add') {
184:             $m = substr($m, 3);
185:             $m[0] = $m[0] | "\x20";
186:             if ($p === 'get') {
187:                 return isset($this->attrs[$m]) ? $this->attrs[$m] : NULL;
188: 
189:             } elseif ($p === 'add') {
190:                 $args[] = TRUE;
191:             }
192:         }
193: 
194:         if (count($args) === 0) { // invalid
195: 
196:         } elseif (count($args) === 1) { // set
197:             $this->attrs[$m] = $args[0];
198: 
199:         } elseif ((string) $args[0] === '') {
200:             $tmp = & $this->attrs[$m]; // appending empty value? -> ignore, but ensure it exists
201: 
202:         } elseif (!isset($this->attrs[$m]) || is_array($this->attrs[$m])) { // needs array
203:             $this->attrs[$m][$args[0]] = $args[1];
204: 
205:         } else {
206:             $this->attrs[$m] = array($this->attrs[$m], $args[0] => $args[1]);
207:         }
208: 
209:         return $this;
210:     }
211: 
212: 
213:     /**
214:      * Special setter for element's attribute.
215:      * @param  string path
216:      * @param  array query
217:      * @return self
218:      */
219:     public function href($path, $query = NULL)
220:     {
221:         if ($query) {
222:             $query = http_build_query($query, NULL, '&');
223:             if ($query !== '') {
224:                 $path .= '?' . $query;
225:             }
226:         }
227:         $this->attrs['href'] = $path;
228:         return $this;
229:     }
230: 
231: 
232:     /**
233:      * Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'.
234:      * @return self
235:      */
236:     public function data($name, $value = NULL)
237:     {
238:         if (func_num_args() === 1) {
239:             $this->attrs['data'] = $name;
240:         } else {
241:             $this->attrs["data-$name"] = is_bool($value) ? json_encode($value) : $value;
242:         }
243:         return $this;
244:     }
245: 
246: 
247:     /**
248:      * Sets element's HTML content.
249:      * @param  string raw HTML string
250:      * @return self
251:      * @throws Nette\InvalidArgumentException
252:      */
253:     public function setHtml($html)
254:     {
255:         if (is_array($html)) {
256:             throw new Nette\InvalidArgumentException(sprintf('Textual content must be a scalar, %s given.', gettype($html)));
257:         }
258:         $this->removeChildren();
259:         $this->children[] = (string) $html;
260:         return $this;
261:     }
262: 
263: 
264:     /**
265:      * Returns element's HTML content.
266:      * @return string
267:      */
268:     public function getHtml()
269:     {
270:         $s = '';
271:         foreach ($this->children as $child) {
272:             if (is_object($child)) {
273:                 $s .= $child->render();
274:             } else {
275:                 $s .= $child;
276:             }
277:         }
278:         return $s;
279:     }
280: 
281: 
282:     /**
283:      * Sets element's textual content.
284:      * @param  string
285:      * @return self
286:      * @throws Nette\InvalidArgumentException
287:      */
288:     public function setText($text)
289:     {
290:         if (!is_array($text) && !$text instanceof self) {
291:             $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8');
292:         }
293:         return $this->setHtml($text);
294:     }
295: 
296: 
297:     /**
298:      * Returns element's textual content.
299:      * @return string
300:      */
301:     public function getText()
302:     {
303:         return html_entity_decode(strip_tags($this->getHtml()), ENT_QUOTES, 'UTF-8');
304:     }
305: 
306: 
307:     /**
308:      * Adds new element's child.
309:      * @param  Html|string Html node or raw HTML string
310:      * @return self
311:      */
312:     public function add($child)
313:     {
314:         return $this->insert(NULL, $child);
315:     }
316: 
317: 
318:     /**
319:      * Creates and adds a new Html child.
320:      * @param  string  elements's name
321:      * @param  array|string element's attributes or raw HTML string
322:      * @return self  created element
323:      */
324:     public function create($name, $attrs = NULL)
325:     {
326:         $this->insert(NULL, $child = static::el($name, $attrs));
327:         return $child;
328:     }
329: 
330: 
331:     /**
332:      * Inserts child node.
333:      * @param  int|NULL position of NULL for appending
334:      * @param  Html|string Html node or raw HTML string
335:      * @param  bool
336:      * @return self
337:      * @throws Nette\InvalidArgumentException
338:      */
339:     public function insert($index, $child, $replace = FALSE)
340:     {
341:         if ($child instanceof self || is_scalar($child)) {
342:             if ($index === NULL) { // append
343:                 $this->children[] = $child;
344: 
345:             } else { // insert or replace
346:                 array_splice($this->children, (int) $index, $replace ? 1 : 0, array($child));
347:             }
348: 
349:         } else {
350:             throw new Nette\InvalidArgumentException(sprintf('Child node must be scalar or Html object, %s given.', is_object($child) ? get_class($child) : gettype($child)));
351:         }
352: 
353:         return $this;
354:     }
355: 
356: 
357:     /**
358:      * Inserts (replaces) child node (\ArrayAccess implementation).
359:      * @param  int|NULL position of NULL for appending
360:      * @param  Html|string Html node or raw HTML string
361:      * @return void
362:      */
363:     public function offsetSet($index, $child)
364:     {
365:         $this->insert($index, $child, TRUE);
366:     }
367: 
368: 
369:     /**
370:      * Returns child node (\ArrayAccess implementation).
371:      * @param  int
372:      * @return self|string
373:      */
374:     public function offsetGet($index)
375:     {
376:         return $this->children[$index];
377:     }
378: 
379: 
380:     /**
381:      * Exists child node? (\ArrayAccess implementation).
382:      * @param  int
383:      * @return bool
384:      */
385:     public function offsetExists($index)
386:     {
387:         return isset($this->children[$index]);
388:     }
389: 
390: 
391:     /**
392:      * Removes child node (\ArrayAccess implementation).
393:      * @param  int
394:      * @return void
395:      */
396:     public function offsetUnset($index)
397:     {
398:         if (isset($this->children[$index])) {
399:             array_splice($this->children, (int) $index, 1);
400:         }
401:     }
402: 
403: 
404:     /**
405:      * Returns children count.
406:      * @return int
407:      */
408:     public function count()
409:     {
410:         return count($this->children);
411:     }
412: 
413: 
414:     /**
415:      * Removed all children.
416:      * @return void
417:      */
418:     public function removeChildren()
419:     {
420:         $this->children = array();
421:     }
422: 
423: 
424:     /**
425:      * Iterates over a elements.
426:      * @return \ArrayIterator
427:      */
428:     public function getIterator()
429:     {
430:         return new \ArrayIterator($this->children);
431:     }
432: 
433: 
434:     /**
435:      * Returns all of children.
436:      * @return array
437:      */
438:     public function getChildren()
439:     {
440:         return $this->children;
441:     }
442: 
443: 
444:     /**
445:      * Renders element's start tag, content and end tag.
446:      * @param  int
447:      * @return string
448:      */
449:     public function render($indent = NULL)
450:     {
451:         $s = $this->startTag();
452: 
453:         if (!$this->isEmpty) {
454:             // add content
455:             if ($indent !== NULL) {
456:                 $indent++;
457:             }
458:             foreach ($this->children as $child) {
459:                 if (is_object($child)) {
460:                     $s .= $child->render($indent);
461:                 } else {
462:                     $s .= $child;
463:                 }
464:             }
465: 
466:             // add end tag
467:             $s .= $this->endTag();
468:         }
469: 
470:         if ($indent !== NULL) {
471:             return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2));
472:         }
473:         return $s;
474:     }
475: 
476: 
477:     public function __toString()
478:     {
479:         return $this->render();
480:     }
481: 
482: 
483:     /**
484:      * Returns element's start tag.
485:      * @return string
486:      */
487:     public function startTag()
488:     {
489:         if ($this->name) {
490:             return '<' . $this->name . $this->attributes() . (static::$xhtml && $this->isEmpty ? ' />' : '>');
491: 
492:         } else {
493:             return '';
494:         }
495:     }
496: 
497: 
498:     /**
499:      * Returns element's end tag.
500:      * @return string
501:      */
502:     public function endTag()
503:     {
504:         return $this->name && !$this->isEmpty ? '</' . $this->name . '>' : '';
505:     }
506: 
507: 
508:     /**
509:      * Returns element's attributes.
510:      * @return string
511:      * @internal
512:      */
513:     public function attributes()
514:     {
515:         if (!is_array($this->attrs)) {
516:             return '';
517:         }
518: 
519:         $s = '';
520:         $attrs = $this->attrs;
521:         if (isset($attrs['data']) && is_array($attrs['data'])) { // deprecated
522:             foreach ($attrs['data'] as $key => $value) {
523:                 $attrs['data-' . $key] = $value;
524:             }
525:             unset($attrs['data']);
526:         }
527: 
528:         foreach ($attrs as $key => $value) {
529:             if ($value === NULL || $value === FALSE) {
530:                 continue;
531: 
532:             } elseif ($value === TRUE) {
533:                 if (static::$xhtml) {
534:                     $s .= ' ' . $key . '="' . $key . '"';
535:                 } else {
536:                     $s .= ' ' . $key;
537:                 }
538:                 continue;
539: 
540:             } elseif (is_array($value)) {
541:                 if (strncmp($key, 'data-', 5) === 0) {
542:                     $value = Json::encode($value);
543: 
544:                 } else {
545:                     $tmp = NULL;
546:                     foreach ($value as $k => $v) {
547:                         if ($v != NULL) { // intentionally ==, skip NULLs & empty string
548:                             //  composite 'style' vs. 'others'
549:                             $tmp[] = $v === TRUE ? $k : (is_string($k) ? $k . ':' . $v : $v);
550:                         }
551:                     }
552:                     if ($tmp === NULL) {
553:                         continue;
554:                     }
555: 
556:                     $value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp);
557:                 }
558: 
559:             } elseif (is_float($value)) {
560:                 $value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');
561: 
562:             } else {
563:                 $value = (string) $value;
564:             }
565: 
566:             $q = strpos($value, '"') === FALSE ? '"' : "'";
567:             $s .= ' ' . $key . '=' . $q
568:                 . str_replace(
569:                     array('&', $q, '<'),
570:                     array('&amp;', $q === '"' ? '&quot;' : '&#39;', self::$xhtml ? '&lt;' : '<'),
571:                     $value
572:                 )
573:                 . (strpos($value, '`') !== FALSE && strpbrk($value, ' <>"\'') === FALSE ? ' ' : '')
574:                 . $q;
575:         }
576: 
577:         $s = str_replace('@', '&#64;', $s);
578:         return $s;
579:     }
580: 
581: 
582:     /**
583:      * Clones all children too.
584:      */
585:     public function __clone()
586:     {
587:         foreach ($this->children as $key => $value) {
588:             if (is_object($value)) {
589:                 $this->children[$key] = clone $value;
590:             }
591:         }
592:     }
593: 
594: }
595: 
Nette 2.3.8 API API documentation generated by ApiGen 2.8.0