Merge pull request #359 from shama/patch-texthelper

Fix TextHelper excerpt method to work as documented
This commit is contained in:
Mark Story 2011-12-06 09:37:09 -08:00
commit a44c4aa291
2 changed files with 23 additions and 25 deletions

View file

@ -354,7 +354,7 @@ class TextHelperTest extends CakeTestCase {
public function testExcerpt() {
$text = 'This is a phrase with test text to play with';
$expected = '...with test text...';
$expected = '...ase with test text to ...';
$result = $this->Text->excerpt($text, 'test', 9, '...');
$this->assertEquals($expected, $result);
@ -370,18 +370,19 @@ class TextHelperTest extends CakeTestCase {
$result = $this->Text->excerpt($text, null, 200, '...');
$this->assertEquals($expected, $result);
$expected = '...phrase...';
$expected = '...a phrase w...';
$result = $this->Text->excerpt($text, 'phrase', 2, '...');
$this->assertEquals($expected, $result);
$phrase = 'This is a phrase with test';
$phrase = 'This is a phrase with test text';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, strlen($phrase) + 3, '...');
$result = $this->Text->excerpt($text, $phrase, 13, '...');
$this->assertEquals($expected, $result);
$phrase = 'This is a phrase with text';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, 10, '...');
$text = 'aaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaa';
$phrase = 'bbbbbbbb';
$result = $this->Text->excerpt($text, $phrase, 10);
$expected = '...aaaaaaaaaabbbbbbbbaaaaaaaaaa...';
$this->assertEquals($expected, $result);
}
@ -393,7 +394,7 @@ class TextHelperTest extends CakeTestCase {
public function testExcerptCaseInsensitivity() {
$text = 'This is a phrase with test text to play with';
$expected = '...with test text...';
$expected = '...ase with test text to ...';
$result = $this->Text->excerpt($text, 'TEST', 9, '...');
$this->assertEquals($expected, $result);

View file

@ -321,34 +321,31 @@ class TextHelper extends AppHelper {
return $this->truncate($text, $radius * 2, array('ending' => $ending));
}
$append = $prepend = $ending;
$phraseLen = mb_strlen($phrase);
if ($radius < $phraseLen) {
$radius = $phraseLen;
}
$textLen = mb_strlen($text);
$pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
$startPos = 0;
if ($pos > $radius) {
$startPos = $pos - $radius;
if ($pos === false) {
return mb_substr($text, 0, $radius) . $ending;
}
$textLen = mb_strlen($text);
$startPos = $pos - $radius;
if ($startPos <= 0) {
$startPos = 0;
$prepend = '';
}
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
$append = '';
}
$excerpt = mb_substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
}
if ($endPos != $textLen) {
$excerpt = substr_replace($excerpt, $ending, -$phraseLen);
}
$excerpt = $prepend . $excerpt . $append;
return $excerpt;
}