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