<?php
class Core_Twig_Extensions_Extension_String extends Twig_Extension
{
    /**
     * Returns a list of filters.
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'nl2br'    => new Twig_Filter_Function('nl2br', array('pre_escape' => 'html', 'is_safe' => array('html'))),
            'trim'     => new Twig_Filter_Function('trim'),
            'str_replace' => new Twig_Filter_Function('core_twig_string_replace'),
            'widont'   => new Twig_Filter_Function('core_twig_string_widont',  array('pre_escape' => 'html', 'is_safe' => array('html'))),
            'wrap'     => new Twig_Filter_Function('core_twig_string_wordwrap'),
            'truncate' => new Twig_Filter_Function('core_twig_string_truncate'),
            'sprintf'  => new Twig_Filter_Function('sprintf')
        );
    }

    /**
     * Name of this extension
     *
     * @return string
     */
    public function getName()
    {
        return 'Core_Twig_String';
    }
}

function core_twig_string_truncate($string, $length = 80, $etc = '&#8230;', $break_words = false) {
    if ($length == 0) {
        return '';
    }
    if (strlen($string) > $length) {
        $length -= strlen($etc);
        $fragment = mb_substr($string, 0, $length + 1);
        if ($break_words) {
            $fragment = mb_substr($fragment, 0, -1);
        } else {
            $fragment = preg_replace('/\s+(\S+)?$/', '', $fragment);
        }
        return $fragment . $etc;
    } else {
        return $string;
    }
}

function core_twig_string_replace($str, $find, $replace)
{
    return str_replace($find, $replace, $str);
}

function core_twig_string_widont($str)
{
    return preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1&nbsp;$2', $str);
}

function core_twig_string_wordwrap($str, $width = 75)
{
    $s=explode(" ", $str);
    $new_string = '';
    foreach ($s as $k=>$v) {
        $cnt = strlen($v);
        if($cnt>$width) {
            $v = wordwrap($v, $width, "\n", true);
        }

        $new_string.="$v ";
    }
    return $new_string;
}