public static truncate ( string $var = null, integer $length, boolean $useHellip = true, boolean $closestWord = false ) : string | ||
$var | string | The string passed from the template. |
$length | integer | The maximum length of the truncated string. |
$useHellip | boolean | Should a hellip be appended if the length exceeds the requested length? |
$closestWord | boolean | Truncate on exact length or on closest word? |
리턴 | string |
public static function truncate($var = null, $length, $useHellip = true, $closestWord = false)
{
// init vars
$charset = BackendModel::getContainer()->getParameter('kernel.charset');
// remove special chars, all of them, also the ones that shouldn't be there.
$var = \SpoonFilter::htmlentitiesDecode($var, null, ENT_QUOTES);
// remove HTML
$var = strip_tags($var);
// less characters
if (mb_strlen($var) <= $length) {
return \SpoonFilter::htmlspecialchars($var);
} else {
// more characters
// hellip is seen as 1 char, so remove it from length
if ($useHellip) {
--$length;
}
// truncate
if ($closestWord) {
$var = mb_substr($var, 0, mb_strrpos(mb_substr($var, 0, $length + 1), ' '), $charset);
} else {
$var = mb_substr($var, 0, $length, $charset);
}
// add hellip
if ($useHellip) {
$var .= '…';
}
// return
return \SpoonFilter::htmlspecialchars($var, ENT_QUOTES);
}
}
public function test_truncate() { $containerMock = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerInterface')->disableOriginalConstructor()->getMock(); $containerMock->expects($this->any())->method('getParameter')->with('kernel.charset')->will($this->returnValue('UTF-8')); BackendModel::setContainer($containerMock); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 3, false, true), 'foo'); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 4, false, true), 'foo'); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 8, false, true), 'foo bar'); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 100, false, true), 'foo bar baz qux'); // Hellip $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 5, true, true), 'foo…'); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 14, true, true), 'foo bar baz…'); $this->assertEquals(TemplateModifiers::truncate('foo bar baz qux', 15, true, true), 'foo bar baz qux'); }