BUGFIX: returns duplicated number of the same sentences (from r78773, r78778)

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@81472 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Sam Minnee 2009-07-09 06:14:04 +00:00
parent f515ed7898
commit a738dc2027
2 changed files with 35 additions and 19 deletions

View File

@ -86,30 +86,25 @@ class Text extends DBField {
* @param int $sentCount The amount of sentences you want. * @param int $sentCount The amount of sentences you want.
*/ */
function LimitSentences($sentCount = 2) { function LimitSentences($sentCount = 2) {
$output = ''; if(!is_numeric($sentCount)) user_error("Text::LimitSentence() expects one numeric argument", E_USER_NOTICE);
$data = Convert::xml2raw($this->value);
$output = array();
$data = trim(Convert::xml2raw($this->value));
$sentences = explode('.', $data); $sentences = explode('.', $data);
if(count($sentences) == 1) {
return $sentences[0] . '.'; if ($sentCount == 0) return '';
} elseif(count($sentences) > 1) {
if(is_numeric($sentCount) && $sentCount != 0) { for($i = 0; $i < $sentCount; $i++) {
if($sentCount == 1) { if(isset($sentences[$i])) {
$output = $sentences[0] . '. '; $sentence = trim($sentences[$i]);
} else { if(!empty($sentence)) $output[] .= $sentence;
for($i = 1; $i <= $sentCount-1; $i++) {
if($sentences[0]) {
$output .= $sentences[0] . '. ';
}
if($sentences[$i]) {
$output .= $sentences[$i] . '. ';
}
}
}
return $output;
} }
} }
return count($output)==0 ? '' : implode($output, '. ') . '.';
} }
/** /**
* Caution: Not XML/HTML-safe - does not respect closing tags. * Caution: Not XML/HTML-safe - does not respect closing tags.
*/ */

View File

@ -66,5 +66,26 @@ class TextTest extends SapphireTest {
} }
} }
/**
* Test {@link Text->LimitSentences()}
*/
function testLimitSentences() {
$cases = array(
'' => '',
'First sentence.' => 'First sentence.',
'First sentence. Second sentence' => 'First sentence. Second sentence.',
'<p>First sentence.</p>' => 'First sentence.',
'<p>First sentence. Second sentence. Third sentence</p>' => 'First sentence. Second sentence.',
'<p>First sentence. <em>Second sentence</em>. Third sentence</p>' => 'First sentence. Second sentence.',
'<p>First sentence. <em class="dummyClass">Second sentence</em>. Third sentence</p>' => 'First sentence. Second sentence.'
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitSentences(2));
}
}
} }
?> ?>