1
0

HtmlHelper.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace fphammerle\helpers;
  3. class HtmlHelper
  4. {
  5. public static function encode($string)
  6. {
  7. return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE);
  8. }
  9. private static function _renderTagAttributes(array $attributes = [])
  10. {
  11. return StringHelper::implode(' ', ArrayHelper::mapIfSet(
  12. $attributes,
  13. function($k, $v) {
  14. if($v === true) {
  15. return sprintf('%s="%s"', $k, $k);
  16. } elseif($v === false) {
  17. return null;
  18. } else {
  19. return sprintf('%s="%s"', $k, self::encode($v));
  20. }
  21. }
  22. ));
  23. }
  24. public static function voidTag($tag_name, array $attributes = [])
  25. {
  26. if($tag_name === null) {
  27. return null;
  28. } elseif(!is_string($tag_name)) {
  29. throw new \TypeError(
  30. sprintf('expected string or null as tag name, %s given', gettype($tag_name))
  31. );
  32. } else {
  33. return sprintf(
  34. '<%s%s />',
  35. $tag_name,
  36. StringHelper::prepend(' ', self::_renderTagAttributes($attributes))
  37. );
  38. }
  39. }
  40. public static function startTag($tag_name, array $attributes = [])
  41. {
  42. if($tag_name === null) {
  43. return null;
  44. } elseif(!is_string($tag_name)) {
  45. throw new \TypeError(
  46. sprintf('expected string or null as tag name, %s given', gettype($tag_name))
  47. );
  48. } else {
  49. return sprintf(
  50. '<%s%s>',
  51. $tag_name,
  52. StringHelper::prepend(' ', self::_renderTagAttributes($attributes))
  53. );
  54. }
  55. }
  56. public static function endTag($name)
  57. {
  58. if($name === null) {
  59. return null;
  60. } elseif(!is_string($name)) {
  61. throw new \TypeError(
  62. sprintf('expected string or null as name, %s given', gettype($name))
  63. );
  64. } else {
  65. return '</' . $name . '>';
  66. }
  67. }
  68. public static function nonVoidTag($tag_name, $content, array $attributes = [])
  69. {
  70. // @see https://www.w3.org/TR/html-markup/syntax.html#syntax-elements
  71. return StringHelper::embed(
  72. self::startTag($tag_name, $attributes),
  73. $content,
  74. self::endTag($tag_name)
  75. );
  76. }
  77. }