MarkupTrait.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Drupal\Component\Render;
  3. /**
  4. * Implements MarkupInterface and Countable for rendered objects.
  5. *
  6. * @see \Drupal\Component\Render\MarkupInterface
  7. */
  8. trait MarkupTrait {
  9. /**
  10. * The safe string.
  11. *
  12. * @var string
  13. */
  14. protected $string;
  15. /**
  16. * Creates a Markup object if necessary.
  17. *
  18. * If $string is equal to a blank string then it is not necessary to create a
  19. * Markup object. If $string is an object that implements MarkupInterface it
  20. * is returned unchanged.
  21. *
  22. * @param mixed $string
  23. * The string to mark as safe. This value will be cast to a string.
  24. *
  25. * @return string|\Drupal\Component\Render\MarkupInterface
  26. * A safe string.
  27. */
  28. public static function create($string) {
  29. if ($string instanceof MarkupInterface) {
  30. return $string;
  31. }
  32. $string = (string) $string;
  33. if ($string === '') {
  34. return '';
  35. }
  36. $safe_string = new static();
  37. $safe_string->string = $string;
  38. return $safe_string;
  39. }
  40. /**
  41. * Returns the string version of the Markup object.
  42. *
  43. * @return string
  44. * The safe string content.
  45. */
  46. public function __toString() {
  47. return $this->string;
  48. }
  49. /**
  50. * Returns the string length.
  51. *
  52. * @return int
  53. * The length of the string.
  54. */
  55. public function count() {
  56. return mb_strlen($this->string);
  57. }
  58. /**
  59. * Returns a representation of the object for use in JSON serialization.
  60. *
  61. * @return string
  62. * The safe string content.
  63. */
  64. public function jsonSerialize() {
  65. return $this->__toString();
  66. }
  67. }