<?php
/**
 * ISO Project
 *
 * @category   Malf
 * @package    Malf_View
 * @subpackage Helper
 * @version    1.0
 */

/** Zend_View_Helper_Abstract.php */
require_once 'Zend/View/Helper/Abstract.php';

/**
 * Smarty truncate modifier plugin
 * 
 * This truncates a variable to a character length, the default is 80.
 *
 * @copyright  Jakub Mrozek <jakub dot mrozek at gmail dot com>
 * @license    LGPL License
 * @link       http://smarty.php.net/manual/en/language.modifier.truncate.php
 * @link       http://weblog.ronnieweb.net/?p=145
 * @author     Jakub Mrozek <jakub dot mrozek at gmail dot com>
 * @author     Monte Ohrt <monte at ohrt dot com>
 * @subpackage Helper
*/
class Malf_View_Helper_Truncate
{
	/**
	 * Truncates a variable to a character length
	 *
	 * @param  string $string
	 * @param  int $length How many characters to truncate to
	 * @param  string $etc Text string that replaces the truncated text
	 * @param  boolean $break_words Truncate at a word boundary with FALSE, or at the exact character with TRUE.
	 * @param  boolean $middle Truncation happens at the end of the string with FALSE, or in the middle of the string with TRUE
	 * @return string
	 */
	public function truncate($string, $length = 80, $etc = '...',
                             $break_words = false, $middle = false)
    {
    	if ($length == 0) {
            return '';
        }
    
        if (strlen($string) > $length) {
            $length -= min($length, strlen($etc));
            if (!$break_words && !$middle) {
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
            }
            if(!$middle) {
                return substr($string, 0, $length) . $etc;
            } else {
                return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
            }
        } else {
            return $string;
        }
    }
}
