annotate core/lib/Drupal/Component/Utility/ToStringTrait.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Component\Utility;
Chris@0 4
Chris@0 5 /**
Chris@0 6 * Wraps __toString in a trait to avoid some fatals.
Chris@0 7 */
Chris@0 8 trait ToStringTrait {
Chris@0 9
Chris@0 10 /**
Chris@0 11 * Implements the magic __toString() method.
Chris@0 12 */
Chris@0 13 public function __toString() {
Chris@0 14 try {
Chris@0 15 return (string) $this->render();
Chris@0 16 }
Chris@0 17 catch (\Exception $e) {
Chris@0 18 // User errors in __toString() methods are considered fatal in the Drupal
Chris@0 19 // error handler.
Chris@0 20 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);
Chris@0 21 // In case we are using another error handler that did not fatal on the
Chris@0 22 // E_USER_ERROR, we terminate execution. However, for test purposes allow
Chris@0 23 // a return value.
Chris@0 24 return $this->_die();
Chris@0 25 }
Chris@0 26 }
Chris@0 27
Chris@0 28 /**
Chris@0 29 * For test purposes, wrap die() in an overridable method.
Chris@0 30 */
Chris@0 31 protected function _die() {
Chris@0 32 die();
Chris@0 33 }
Chris@0 34
Chris@0 35 /**
Chris@0 36 * Renders the object as a string.
Chris@0 37 *
Chris@0 38 * @return string|object
Chris@0 39 * The rendered string or an object implementing __toString().
Chris@0 40 */
Chris@0 41 abstract public function render();
Chris@0 42
Chris@0 43 }