Moving parameters to $options on Text::truncate() and Text::highlight().

This commit is contained in:
renan.saddam 2009-10-29 01:23:44 -02:00
parent 6c18c0e0c7
commit e7074c1e5c
2 changed files with 67 additions and 53 deletions

View file

@ -46,43 +46,51 @@ class TextHelper extends AppHelper {
* Highlights a given phrase in a text. You can specify any expression in highlighter that * Highlights a given phrase in a text. You can specify any expression in highlighter that
* may include the \1 expression to include the $phrase found. * may include the \1 expression to include the $phrase found.
* *
* Options:
*
* - 'format' The piece of html with that the phrase will be highlighted
* - 'html' If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
*
* @param string $text Text to search the phrase in * @param string $text Text to search the phrase in
* @param string $phrase The phrase that will be searched * @param string $phrase The phrase that will be searched
* @param string $highlighter The piece of html with that the phrase will be highlighted * @param array $options An array of html attributes and options.
* @param boolean $considerHtml If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
* @return string The highlighted text * @return string The highlighted text
* @access public * @access public
*/ */
function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>', $considerHtml = false) { function highlight($text, $phrase, $options = array()) {
if (empty($phrase)) { if (empty($phrase)) {
return $text; return $text;
} }
if (is_array($phrase)) { $default = array(
'format' => '<span class="highlight">\1</span>',
'html' => false
);
$options = array_merge($default, $options);
extract($options);
if (is_array($phrase)) {
$replace = array(); $replace = array();
$with = array(); $with = array();
foreach ($phrase as $key => $segment) { foreach ($phrase as $key => $segment) {
$segment = "($segment)"; $segment = "($segment)";
if ($html) {
if ($considerHtml) {
$segment = "(?![^<]+>)$segment(?![^<]+>)"; $segment = "(?![^<]+>)$segment(?![^<]+>)";
} }
$with[] = (is_array($highlighter)) ? $highlighter[$key] : $highlighter; $with[] = (is_array($format)) ? $format[$key] : $format;
$replace[] = "|$segment|iu"; $replace[] = "|$segment|iu";
} }
return preg_replace($replace, $with, $text); return preg_replace($replace, $with, $text);
} else { } else {
$phrase = "($phrase)"; $phrase = "($phrase)";
if ($considerHtml) { if ($html) {
$phrase = "(?![^<]+>)$phrase(?![^<]+>)"; $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
} }
return preg_replace("|$phrase|iu", $highlighter, $text); return preg_replace("|$phrase|iu", $format, $text);
} }
} }
@ -160,24 +168,32 @@ class TextHelper extends AppHelper {
* Cuts a string to the length of $length and replaces the last characters * Cuts a string to the length of $length and replaces the last characters
* with the ending if the text is longer than length. * with the ending if the text is longer than length.
* *
* Options:
*
* - 'ending' Will be used as Ending and appended to the trimmed string
* - 'exact' If false, $text will not be cut mid-word
* - 'html' If true, HTML tags would be handled correctly
*
* @param string $text String to truncate. * @param string $text String to truncate.
* @param integer $length Length of returned string, including ellipsis. * @param integer $length Length of returned string, including ellipsis.
* @param mixed $ending If string, will be used as Ending and appended to the trimmed string. Can also be an associative array that can contain the last three params of this method. * @param array $options An array of html attributes and options.
* @param boolean $exact If false, $text will not be cut mid-word
* @param boolean $considerHtml If true, HTML tags would be handled correctly
* @return string Trimmed string. * @return string Trimmed string.
*/ */
function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) { function truncate($text, $length = 100, $options = array()) {
if (is_array($ending)) { $default = array(
extract($ending); 'ending' => '...', 'exact' => true, 'html' => false
} );
if ($considerHtml) { $options = array_merge($default, $options);
extract($options);
if ($html) {
if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
return $text; return $text;
} }
$totalLength = mb_strlen($ending); $totalLength = mb_strlen($ending);
$openTags = array(); $openTags = array();
$truncate = ''; $truncate = '';
preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
foreach ($tags as $tag) { foreach ($tags as $tag) {
if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) { if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
@ -217,7 +233,6 @@ class TextHelper extends AppHelper {
break; break;
} }
} }
} else { } else {
if (mb_strlen($text) <= $length) { if (mb_strlen($text) <= $length) {
return $text; return $text;
@ -228,7 +243,7 @@ class TextHelper extends AppHelper {
if (!$exact) { if (!$exact) {
$spacepos = mb_strrpos($truncate, ' '); $spacepos = mb_strrpos($truncate, ' ');
if (isset($spacepos)) { if (isset($spacepos)) {
if ($considerHtml) { if ($html) {
$bits = mb_substr($truncate, $spacepos); $bits = mb_substr($truncate, $spacepos);
preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER); preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
if (!empty($droppedTags)) { if (!empty($droppedTags)) {
@ -242,10 +257,9 @@ class TextHelper extends AppHelper {
$truncate = mb_substr($truncate, 0, $spacepos); $truncate = mb_substr($truncate, 0, $spacepos);
} }
} }
$truncate .= $ending; $truncate .= $ending;
if ($considerHtml) { if ($html) {
foreach ($openTags as $tag) { foreach ($openTags as $tag) {
$truncate .= '</'.$tag.'>'; $truncate .= '</'.$tag.'>';
} }
@ -276,9 +290,9 @@ class TextHelper extends AppHelper {
* @return string Modified string * @return string Modified string
* @access public * @access public
*/ */
function excerpt($text, $phrase, $radius = 100, $ending = "...") { function excerpt($text, $phrase, $radius = 100, $ending = '...') {
if (empty($text) or empty($phrase)) { if (empty($text) or empty($phrase)) {
return $this->truncate($text, $radius * 2, $ending); return $this->truncate($text, $radius * 2, array('ending' => $ending));
} }
$phraseLen = mb_strlen($phrase); $phraseLen = mb_strlen($phrase);

View file

@ -77,25 +77,24 @@ class TextHelperTest extends CakeTestCase {
$text9 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь'; $text9 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь';
$this->assertIdentical($this->Text->truncate($text1, 15), 'The quick br...'); $this->assertIdentical($this->Text->truncate($text1, 15), 'The quick br...');
$this->assertIdentical($this->Text->truncate($text1, 15, '...', false), 'The quick...'); $this->assertIdentical($this->Text->truncate($text1, 15, array('exact' => false)), 'The quick...');
$this->assertIdentical($this->Text->truncate($text1, 100), 'The quick brown fox jumps over the lazy dog'); $this->assertIdentical($this->Text->truncate($text1, 100), 'The quick brown fox jumps over the lazy dog');
$this->assertIdentical($this->Text->truncate($text2, 10, '...'), 'Heiz&ou...'); $this->assertIdentical($this->Text->truncate($text2, 10), 'Heiz&ou...');
$this->assertIdentical($this->Text->truncate($text2, 10, '...', false), '...'); $this->assertIdentical($this->Text->truncate($text2, 10, array('exact' => false)), '...');
$this->assertIdentical($this->Text->truncate($text3, 20), '<b>&copy; 2005-20...'); $this->assertIdentical($this->Text->truncate($text3, 20), '<b>&copy; 2005-20...');
$this->assertIdentical($this->Text->truncate($text4, 15), '<img src="my...'); $this->assertIdentical($this->Text->truncate($text4, 15), '<img src="my...');
$this->assertIdentical($this->Text->truncate($text5, 6, ''), '0<b>1<'); $this->assertIdentical($this->Text->truncate($text5, 6, array('ending' => '')), '0<b>1<');
$this->assertIdentical($this->Text->truncate($text1, 15, array('ending' => '...', 'exact' => true, 'considerHtml' => true)), 'The quick br...'); $this->assertIdentical($this->Text->truncate($text1, 15, array('html' => true)), 'The quick br...');
$this->assertIdentical($this->Text->truncate($text1, 15, '...', true, true), 'The quick br...'); $this->assertIdentical($this->Text->truncate($text1, 15, array('exact' => false, 'html' => true)), 'The quick...');
$this->assertIdentical($this->Text->truncate($text1, 15, '...', false, true), 'The quick...'); $this->assertIdentical($this->Text->truncate($text2, 10, array('html' => true)), 'Heiz&ouml;lr...');
$this->assertIdentical($this->Text->truncate($text2, 10, '...', true, true), 'Heiz&ouml;lr...'); $this->assertIdentical($this->Text->truncate($text2, 10, array('exact' => false, 'html' => true)), '...');
$this->assertIdentical($this->Text->truncate($text2, 10, '...', false, true), '...'); $this->assertIdentical($this->Text->truncate($text3, 20, array('html' => true)), '<b>&copy; 2005-2007, Cake...</b>');
$this->assertIdentical($this->Text->truncate($text3, 20, '...', true, true), '<b>&copy; 2005-2007, Cake...</b>'); $this->assertIdentical($this->Text->truncate($text4, 15, array('html' => true)), '<img src="mypic.jpg"> This image ...');
$this->assertIdentical($this->Text->truncate($text4, 15, '...', true, true), '<img src="mypic.jpg"> This image ...'); $this->assertIdentical($this->Text->truncate($text4, 45, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But t...</b>');
$this->assertIdentical($this->Text->truncate($text4, 45, '...', true, true), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But t...</b>'); $this->assertIdentical($this->Text->truncate($text4, 90, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Grea...');
$this->assertIdentical($this->Text->truncate($text4, 90, '...', true, true), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Grea...'); $this->assertIdentical($this->Text->truncate($text5, 6, array('ending' => '', 'html' => true)), '0<b>1<i>2<span class="myclass">3</span>4<u>5</u></i></b>');
$this->assertIdentical($this->Text->truncate($text5, 6, '', true, true), '0<b>1<i>2<span class="myclass">3</span>4<u>5</u></i></b>'); $this->assertIdentical($this->Text->truncate($text5, 20, array('ending' => '', 'html' => true)), $text5);
$this->assertIdentical($this->Text->truncate($text5, 20, '', true, true), $text5); $this->assertIdentical($this->Text->truncate($text6, 57, array('exact' => false, 'html' => true)), "<p><strong>Extra dates have been announced for this year's...</strong></p>");
$this->assertIdentical($this->Text->truncate($text6, 57, '...', false, true), "<p><strong>Extra dates have been announced for this year's...</strong></p>");
$this->assertIdentical($this->Text->truncate($text7, 255), $text7); $this->assertIdentical($this->Text->truncate($text7, 255), $text7);
$this->assertIdentical($this->Text->truncate($text7, 15), 'El moño está...'); $this->assertIdentical($this->Text->truncate($text7, 15), 'El moño está...');
$this->assertIdentical($this->Text->truncate($text8, 15), 'Vive la R'.chr(195).chr(169).'pu...'); $this->assertIdentical($this->Text->truncate($text8, 15), 'Vive la R'.chr(195).chr(169).'pu...');
@ -111,46 +110,47 @@ class TextHelperTest extends CakeTestCase {
function testHighlight() { function testHighlight() {
$text = 'This is a test text'; $text = 'This is a test text';
$phrases = array('This', 'text'); $phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, '<b>\1</b>'); $result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$expected = '<b>This</b> is a test <b>text</b>'; $expected = '<b>This</b> is a test <b>text</b>';
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$text = 'This is a test text'; $text = 'This is a test text';
$phrases = null; $phrases = null;
$result = $this->Text->highlight($text, $phrases, '<b>\1</b>'); $result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEqual($result, $text); $this->assertEqual($result, $text);
$text = 'Ich saß in einem Café am Übergang'; $text = 'Ich saß in einem Café am Übergang';
$expected = 'Ich <b>saß</b> in einem <b>Café</b> am <b>Übergang</b>'; $expected = 'Ich <b>saß</b> in einem <b>Café</b> am <b>Übergang</b>';
$phrases = array('saß', 'café', 'übergang'); $phrases = array('saß', 'café', 'übergang');
$result = $this->Text->highlight($text, $phrases, '<b>\1</b>'); $result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/** /**
* testHighlightConsiderHtml method * testHighlightHtml method
* *
* @access public * @access public
* @return void * @return void
*/ */
function testHighlightConsiderHtml() { function testHighlightHtml() {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>'; $text1 = '<p>strongbow isn&rsquo;t real cider</p>';
$text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>'; $text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>';
$text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />'; $text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$text4 = 'What a strong mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />'; $text4 = 'What a strong mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$options = array('format' => '<b>\1</b>', 'html' => true);
$expected = '<p><b>strong</b>bow isn&rsquo;t real cider</p>'; $expected = '<p><b>strong</b>bow isn&rsquo;t real cider</p>';
$this->assertEqual($this->Text->highlight($text1, 'strong', '<b>\1</b>', true), $expected); $this->assertEqual($this->Text->highlight($text1, 'strong', $options), $expected);
$expected = '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>'; $expected = '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>';
$this->assertEqual($this->Text->highlight($text2, 'strong', '<b>\1</b>', true), $expected); $this->assertEqual($this->Text->highlight($text2, 'strong', $options), $expected);
$this->assertEqual($this->Text->highlight($text3, 'strong', '<b>\1</b>', true), $text3); $this->assertEqual($this->Text->highlight($text3, 'strong', $options), $text3);
$this->assertEqual($this->Text->highlight($text3, array('strong', 'what'), '<b>\1</b>', true), $text3); $this->assertEqual($this->Text->highlight($text3, array('strong', 'what'), $options), $text3);
$expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />'; $expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEqual($this->Text->highlight($text4, array('strong', 'what'), '<b>\1</b>', true), $expected); $this->assertEqual($this->Text->highlight($text4, array('strong', 'what'), $options), $expected);
} }
/** /**
@ -162,7 +162,7 @@ class TextHelperTest extends CakeTestCase {
function testHighlightMulti() { function testHighlightMulti() {
$text = 'This is a test text'; $text = 'This is a test text';
$phrases = array('This', 'text'); $phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, array('<b>\1</b>', '<em>\1</em>')); $result = $this->Text->highlight($text, $phrases, array('format' => array('<b>\1</b>', '<em>\1</em>')));
$expected = '<b>This</b> is a test <em>text</em>'; $expected = '<b>This</b> is a test <em>text</em>';
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
@ -286,10 +286,10 @@ class TextHelperTest extends CakeTestCase {
$text = 'This is a Test text'; $text = 'This is a Test text';
$expected = 'This is a <b>Test</b> text'; $expected = 'This is a <b>Test</b> text';
$result = $this->Text->highlight($text, 'test', '<b>\1</b>'); $result = $this->Text->highlight($text, 'test', array('format' => '<b>\1</b>'));
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$result = $this->Text->highlight($text, array('test'), '<b>\1</b>'); $result = $this->Text->highlight($text, array('test'), array('format' => '<b>\1</b>'));
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
} }