Source for file Html.php

Documentation is available at Html.php

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