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