ENHANCEMENT Strip tags before limiting characters when using LimitCharacters() on HTMLText field type

MINOR Added test to TextTest for LimitCharacters()
MINOR Added test HTMLTextTest and added test case for LimitCharacters()



git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@71795 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Sean Harvey 2009-02-12 09:38:43 +00:00
parent e9757a57b2
commit 7a065b087a
3 changed files with 55 additions and 0 deletions

View File

@ -8,6 +8,20 @@
*/
class HTMLText extends Text {
/**
* Limit this field's content by a number of characters.
* This makes use of strip_tags() to avoid malforming the
* HTML tags in the string of text.
*
* @param int $limit Number of characters to limit by
* @param string $add Ellipsis to add to the end of truncated string
* @return string
*/
function LimitCharacters($limit = 20, $add = "...") {
$value = trim(strip_tags($this->value));
return (strlen($value) > $limit) ? substr($value, 0, $limit) . $add : $value;
}
/**
* Create a summary of the content. This will either be the first paragraph, or the first $maxWords
* words, whichever is shorter

View File

@ -0,0 +1,25 @@
<?php
/**
* @package sapphire
* @subpackage tests
*/
class HTMLTextTest extends SapphireTest {
/**
* Test {@link Text->LimitCharacters()}
*/
function testLimitCharacters() {
$cases = array(
'The little brown fox jumped over the lazy cow.' => 'The little brown fox...',
'<p>This is some text in a paragraph.</p>' => 'This is some text in...'
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new HTMLText('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitCharacters());
}
}
}
?>

View File

@ -4,6 +4,22 @@
* @subpackage tests
*/
class TextTest extends SapphireTest {
/**
* Test {@link Text->LimitCharacters()}
*/
function testLimitCharacters() {
$cases = array(
'The little brown fox jumped over the lazy cow.' => 'The little brown fox...',
'<p>This is some text in a paragraph.</p>' => '<p>This is some text...'
);
foreach($cases as $originalValue => $expectedValue) {
$textObj = new Text('Test');
$textObj->setValue($originalValue);
$this->assertEquals($expectedValue, $textObj->LimitCharacters());
}
}
/**
* Test {@link Text->LimitWordCount()}