From e36247c1ed5421a93eba491371e9febdf5ab6012 Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Fri, 15 Oct 2010 02:59:46 +0000 Subject: [PATCH] ENHANCEMENT: added prefix and suffix support to ContextSummary (from r106200) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@112526 467b73ca-7a2a-4603-9d3b-597d59a354a9 --- core/model/fieldtypes/Text.php | 21 +++++++++++++++------ tests/fieldtypes/TextTest.php | 6 ++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/core/model/fieldtypes/Text.php b/core/model/fieldtypes/Text.php index 38d42ba7f..1f4defb99 100644 --- a/core/model/fieldtypes/Text.php +++ b/core/model/fieldtypes/Text.php @@ -266,9 +266,12 @@ class Text extends StringField { * @param boolean $string Supplied string ("keywords") * @param boolean $striphtml Strip HTML? * @param boolean $highlight Add a highlight element around search query? + * @param String prefix text + * @param String suffix + * * @return string */ - function ContextSummary($characters = 500, $string = false, $striphtml = true, $highlight = true) { + function ContextSummary($characters = 500, $string = false, $striphtml = true, $highlight = true, $prefix = "... ", $suffix = "...") { if(!$string) $string = $_REQUEST['Search']; // Use the default "Search" request variable (from SearchForm) // Remove HTML tags so we don't have to deal with matching tags @@ -279,23 +282,29 @@ class Text extends StringField { // We want to search string to be in the middle of our block to give it some context $position = max(0, $position - ($characters / 2)); - + if($position > 0) { // We don't want to start mid-word $position = max((int) strrpos(substr($text, 0, $position), ' '), (int) strrpos(substr($text, 0, $position), "\n")); } - + $summary = substr($text, $position, $characters); $stringPieces = explode(' ', $string); if($highlight) { // Add a span around all key words from the search term as well - if($stringPieces) foreach($stringPieces as $stringPiece) { - $summary = str_ireplace($stringPiece, "$stringPiece", $summary); + if($stringPieces) { + foreach($stringPieces as $stringPiece) { + $summary = str_ireplace($stringPiece, "$stringPiece", $summary); + } } } + $summary = trim($summary); - return trim($summary); + if($position > 0) $summary = $prefix . $summary; + if(strlen($this->value) > ($characters + $position)) $summary = $summary . $suffix; + + return $summary; } /** diff --git a/tests/fieldtypes/TextTest.php b/tests/fieldtypes/TextTest.php index 233d6c77c..3b961f912 100644 --- a/tests/fieldtypes/TextTest.php +++ b/tests/fieldtypes/TextTest.php @@ -122,7 +122,5 @@ class TextTest extends SapphireTest { 'This is some test text. test test what if you have', $textObj->ContextSummary(50, $testKeywords2) ); - } - -} -?> + } +} \ No newline at end of file