Echo89

Improved Text Cutter (ProcessWire Hook)

Aug 1st, 2016
117
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $wire->addHook('Page::summarize', function($event) {
  2.     $fieldName = $event->arguments(0);
  3.     if(!$fieldName) throw new WireException("No field provided");
  4.  
  5.     // get max length or use 300 as default if none provided
  6.     $maxLength = (int) $event->arguments(1);
  7.     if(!$maxLength) $maxLength = 300;
  8.    
  9.     $ending = $event->arguments(2);
  10.     if(!$ending) $ending = '…';
  11.    
  12.     $ending = html_entity_decode($ending);
  13.    
  14.     if($maxLength <= 0) {
  15.         throw new WireException("The max length cannot be less than or equal to the length of the appended ending");
  16.     }
  17.  
  18.     $page = $event->object;
  19.     $value = strip_tags(html_entity_decode((string) $page->get($fieldName)));
  20.    
  21.     if(mb_strlen($value) > $maxLength) {
  22.         $event->return = $value;
  23.    
  24.         // Subtract length of decoded ending from the maxLength, as this function
  25.         // should return a string no longer than $maxLength, and the ending should
  26.         // be included within that.
  27.         $maxLength -= mb_strlen($ending);
  28.        
  29.         // Don't cut on a non-alphabetic char
  30.         while(!ctype_alpha($value[$maxLength-1])) {
  31.             $maxLength--;
  32.             if($maxLength <= 0) break;
  33.         }
  34.        
  35.         $value = mb_substr($value, 0, $maxLength);
  36.        
  37.         $value .= $ending;
  38.     }
  39.  
  40.     // if output formatting on, make sure value is entity encoded
  41.     if($page->of()) $value = $event->sanitizer->entities1($value);
  42.  
  43.     $event->return = $value;
  44. });
RAW Paste Data