HtmlHelper.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. public static function startTag($tag_name, array $attributes = [])
  10. {
  11. if($tag_name === null) {
  12. return null;
  13. } elseif(!is_string($tag_name)) {
  14. throw new \TypeError(
  15. sprintf('expected string or null as tag name, %s given', gettype($tag_name))
  16. );
  17. } else {
  18. $rendered_attributes = StringHelper::implode(' ', ArrayHelper::mapIfSet(
  19. $attributes,
  20. function($k, $v) {
  21. if($v === true) {
  22. return sprintf('%s="%s"', $k, $k);
  23. } elseif($v === false) {
  24. return null;
  25. } else {
  26. return sprintf('%s="%s"', $k, self::encode($v));
  27. }
  28. }
  29. ));
  30. return '<' . $tag_name . StringHelper::prepend(' ', $rendered_attributes) . '>';
  31. }
  32. }
  33. public static function endTag($name)
  34. {
  35. if($name === null) {
  36. return null;
  37. } elseif(!is_string($name)) {
  38. throw new \TypeError(
  39. sprintf('expected string or null as name, %s given', gettype($name))
  40. );
  41. } else {
  42. return '</' . $name . '>';
  43. }
  44. }
  45. }