/**
  * Returns a string truncated to fit inside a meta.
  *
  * @param mixed $obj - object that has the schema
  *                     (Node | NodeRef | Element | Aspect)
  * @param string $metaName
  * @param string $string - string to be truncated
  * @param bool $ellipsis - if set, output is appended with three dots
  * @return string
  */
 public static function truncateToMax($obj, $metaName, $string, $ellipsis = false)
 {
     switch (true) {
         case $obj instanceof Element:
         case $obj instanceof Aspect:
             break;
         case $obj instanceof NodeRef:
         case $obj instanceof Node:
             $obj = $obj->Element;
             break;
         default:
             throw new Exception(__CLASS__ . '::' . __FUNCTION__ . ": Expected first argument to be instance of Element, Aspect, Node or NodeRef");
     }
     $metaValidationArray = $obj->Schema->getMetaDef($metaName)->Validation->toArray();
     $max = $metaValidationArray['max'];
     $maxBytes = max($max, 255);
     $truncated = false;
     if (strlen($string) > $maxBytes) {
         $truncated = true;
         $string = StringUtils::utf8SafeTruncate($string, $maxBytes - ($ellipsis ? 3 : 0));
     }
     if ($max < 255 && StringUtils::charCount($string) > $max) {
         $truncated = true;
         $string = StringUtils::utf8Substr($string, 0, $max - ($ellipsis ? 1 : 0));
     }
     return $string . ($truncated && $ellipsis ? "…" : '');
 }