MarkupTrait.php 1.6 KB

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