EncodedHtmlString.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Illuminate\Support;
  3. use BackedEnum;
  4. use Illuminate\Contracts\Support\DeferringDisplayableValue;
  5. use Illuminate\Contracts\Support\Htmlable;
  6. class EncodedHtmlString extends HtmlString
  7. {
  8. /**
  9. * The HTML string.
  10. *
  11. * @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null
  12. */
  13. protected $html;
  14. /**
  15. * The callback that should be used to encode the HTML strings.
  16. *
  17. * @var callable|null
  18. */
  19. protected static $encodeUsingFactory;
  20. /**
  21. * Create a new encoded HTML string instance.
  22. *
  23. * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html
  24. * @param bool $doubleEncode
  25. */
  26. public function __construct($html = '', protected bool $doubleEncode = true)
  27. {
  28. parent::__construct($html);
  29. }
  30. /**
  31. * Convert the special characters in the given value.
  32. *
  33. * @internal
  34. *
  35. * @param string|null $value
  36. * @param int $withQuote
  37. * @param bool $doubleEncode
  38. * @return string
  39. */
  40. public static function convert($value, bool $withQuote = true, bool $doubleEncode = true)
  41. {
  42. $flag = $withQuote ? ENT_QUOTES : ENT_NOQUOTES;
  43. return htmlspecialchars($value ?? '', $flag | ENT_SUBSTITUTE, 'UTF-8', $doubleEncode);
  44. }
  45. /**
  46. * Get the HTML string.
  47. *
  48. * @return string
  49. */
  50. #[\Override]
  51. public function toHtml()
  52. {
  53. $value = $this->html;
  54. if ($value instanceof DeferringDisplayableValue) {
  55. $value = $value->resolveDisplayableValue();
  56. }
  57. if ($value instanceof Htmlable) {
  58. return $value->toHtml();
  59. }
  60. if ($value instanceof BackedEnum) {
  61. $value = $value->value;
  62. }
  63. return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) {
  64. return static::convert($value, doubleEncode: $doubleEncode);
  65. })($value, $this->doubleEncode);
  66. }
  67. /**
  68. * Set the callable that will be used to encode the HTML strings.
  69. *
  70. * @param callable|null $factory
  71. * @return void
  72. */
  73. public static function encodeUsing(?callable $factory = null)
  74. {
  75. static::$encodeUsingFactory = $factory;
  76. }
  77. /**
  78. * Flush the class's global state.
  79. *
  80. * @return void
  81. */
  82. public static function flushState()
  83. {
  84. static::$encodeUsingFactory = null;
  85. }
  86. }