Renderer.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace Knp\Menu\Renderer;
  3. if (!defined('ENT_SUBSTITUTE')) {
  4. define('ENT_SUBSTITUTE', 8);
  5. }
  6. abstract class Renderer
  7. {
  8. protected $charset = 'UTF-8';
  9. /**
  10. * @param string $charset
  11. */
  12. public function __construct($charset = null)
  13. {
  14. if (null !== $charset) {
  15. $this->charset = (string) $charset;
  16. }
  17. }
  18. /**
  19. * Renders a HTML attribute
  20. *
  21. * @param string $name
  22. * @param string $value
  23. * @return string
  24. */
  25. protected function renderHtmlAttribute($name, $value)
  26. {
  27. if (true === $value) {
  28. return sprintf('%s="%s"', $name, $this->escape($name));
  29. }
  30. return sprintf('%s="%s"', $name, $this->escape($value));
  31. }
  32. /**
  33. * Renders HTML attributes
  34. *
  35. * @param array $attributes
  36. * @return string
  37. */
  38. protected function renderHtmlAttributes(array $attributes)
  39. {
  40. return implode('', array_map(array($this, 'htmlAttributesCallback'), array_keys($attributes), array_values($attributes)));
  41. }
  42. /**
  43. * Prepares an attribute key and value for HTML representation.
  44. *
  45. * It removes empty attributes.
  46. *
  47. * @param string $name The attribute name
  48. * @param string $value The attribute value
  49. *
  50. * @return string The HTML representation of the HTML key attribute pair.
  51. */
  52. private function htmlAttributesCallback($name, $value)
  53. {
  54. if (false === $value || null === $value) {
  55. return '';
  56. }
  57. return ' '.$this->renderHtmlAttribute($name, $value);
  58. }
  59. /**
  60. * Escapes an HTML value
  61. *
  62. * @param string $value
  63. * @return string
  64. */
  65. protected function escape($value)
  66. {
  67. return $this->fixDoubleEscape(htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, $this->charset));
  68. }
  69. /**
  70. * Fixes double escaped strings.
  71. *
  72. * @param string $escaped string to fix
  73. * @return string A single escaped string
  74. */
  75. protected function fixDoubleEscape($escaped)
  76. {
  77. return preg_replace('/&amp;([a-z]+|(#\d+)|(#x[\da-f]+));/i', '&$1;', $escaped);
  78. }
  79. /**
  80. * Get the HTML charset
  81. *
  82. * @return string
  83. */
  84. public function getCharset()
  85. {
  86. return $this->charset;
  87. }
  88. /**
  89. * Set the HTML charset
  90. *
  91. * @param string $charset
  92. */
  93. public function setCharset($charset)
  94. {
  95. $this->charset = (string) $charset;
  96. }
  97. }