ToStringTrait.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Wraps __toString in a trait to avoid some fatals.
  5. */
  6. trait ToStringTrait {
  7. /**
  8. * Implements the magic __toString() method.
  9. */
  10. public function __toString() {
  11. try {
  12. return (string) $this->render();
  13. }
  14. catch (\Exception $e) {
  15. // User errors in __toString() methods are considered fatal in the Drupal
  16. // error handler.
  17. trigger_error(get_class($e) . ' thrown while calling __toString on a ' . get_class($this) . ' object in ' . $e->getFile() . ' on line ' . $e->getLine() . ': ' . $e->getMessage(), E_USER_ERROR);
  18. // In case we are using another error handler that did not fatal on the
  19. // E_USER_ERROR, we terminate execution. However, for test purposes allow
  20. // a return value.
  21. return $this->_die();
  22. }
  23. }
  24. /**
  25. * For test purposes, wrap die() in an overridable method.
  26. */
  27. protected function _die() {
  28. die();
  29. }
  30. /**
  31. * Renders the object as a string.
  32. *
  33. * @return string|object
  34. * The rendered string or an object implementing __toString().
  35. */
  36. abstract public function render();
  37. }