You are here

trait SafeStringTrait in Service Container 7.2

Same name and namespace in other branches
  1. 7 lib/Drupal/Component/Utility/SafeStringTrait.php \Drupal\Component\Utility\SafeStringTrait

Implements SafeStringInterface and Countable for rendered objects.

Hierarchy

See also

\Drupal\Component\Utility\SafeStringInterface

File

lib/Drupal/Component/Utility/SafeStringTrait.php, line 15
Contains \Drupal\Component\Utility\SafeStringTrait.

Namespace

Drupal\Component\Utility
View source
trait SafeStringTrait {

  /**
   * The safe string.
   *
   * @var string
   */
  protected $string;

  /**
   * Creates a SafeString object if necessary.
   *
   * If $string is equal to a blank string then it is not necessary to create a
   * SafeString object. If $string is an object that implements
   * SafeStringInterface it is returned unchanged.
   *
   * @param mixed $string
   *   The string to mark as safe. This value will be cast to a string.
   *
   * @return string|\Drupal\Component\Utility\SafeStringInterface
   *   A safe string.
   */
  public static function create($string) {
    if ($string instanceof SafeStringInterface) {
      return $string;
    }
    $string = (string) $string;
    if ($string === '') {
      return '';
    }
    $safe_string = new static();
    $safe_string->string = $string;
    return $safe_string;
  }

  /**
   * Returns the string version of the SafeString object.
   *
   * @return string
   *   The safe string content.
   */
  public function __toString() {
    return $this->string;
  }

  /**
   * Returns the string length.
   *
   * @return int
   *   The length of the string.
   */
  public function count() {
    return Unicode::strlen($this->string);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
SafeStringTrait::$string protected property The safe string.
SafeStringTrait::count public function Returns the string length.
SafeStringTrait::create public static function Creates a SafeString object if necessary.
SafeStringTrait::__toString public function Returns the string version of the SafeString object.