From a738dc20276102bfa36e53d47e69d6a09de1333a Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Thu, 9 Jul 2009 06:14:04 +0000 Subject: [PATCH] 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 --- core/model/fieldtypes/Text.php | 33 ++++++++++++++------------------- tests/fieldtypes/TextTest.php | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/core/model/fieldtypes/Text.php b/core/model/fieldtypes/Text.php index bfc3baec0..e0600c809 100644 --- a/core/model/fieldtypes/Text.php +++ b/core/model/fieldtypes/Text.php @@ -86,30 +86,25 @@ class Text extends DBField { * @param int $sentCount The amount of sentences you want. */ function LimitSentences($sentCount = 2) { - $output = ''; - $data = Convert::xml2raw($this->value); + if(!is_numeric($sentCount)) user_error("Text::LimitSentence() expects one numeric argument", E_USER_NOTICE); + + $output = array(); + $data = trim(Convert::xml2raw($this->value)); $sentences = explode('.', $data); - if(count($sentences) == 1) { - return $sentences[0] . '.'; - } elseif(count($sentences) > 1) { - if(is_numeric($sentCount) && $sentCount != 0) { - if($sentCount == 1) { - $output = $sentences[0] . '. '; - } else { - for($i = 1; $i <= $sentCount-1; $i++) { - if($sentences[0]) { - $output .= $sentences[0] . '. '; - } - if($sentences[$i]) { - $output .= $sentences[$i] . '. '; - } - } - } - return $output; + + if ($sentCount == 0) return ''; + + for($i = 0; $i < $sentCount; $i++) { + if(isset($sentences[$i])) { + $sentence = trim($sentences[$i]); + if(!empty($sentence)) $output[] .= $sentence; } } + + return count($output)==0 ? '' : implode($output, '. ') . '.'; } + /** * Caution: Not XML/HTML-safe - does not respect closing tags. */ diff --git a/tests/fieldtypes/TextTest.php b/tests/fieldtypes/TextTest.php index c59ec825e..db84a4a66 100644 --- a/tests/fieldtypes/TextTest.php +++ b/tests/fieldtypes/TextTest.php @@ -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.', + '

First sentence.

' => 'First sentence.', + '

First sentence. Second sentence. Third sentence

' => 'First sentence. Second sentence.', + '

First sentence. Second sentence. Third sentence

' => 'First sentence. Second sentence.', + '

First sentence. Second sentence. Third sentence

' => 'First sentence. Second sentence.' + ); + + foreach($cases as $originalValue => $expectedValue) { + $textObj = new Text('Test'); + $textObj->setValue($originalValue); + $this->assertEquals($expectedValue, $textObj->LimitSentences(2)); + } + } + } ?> \ No newline at end of file