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