From 53bfc8cca2263467a2dbbc628e85d51aafb2b767 Mon Sep 17 00:00:00 2001 From: dogmatic Date: Tue, 24 Nov 2009 22:12:57 +0200 Subject: [PATCH] a new take on toList and more tests for passing a different separator --- cake/libs/view/helpers/text.php | 14 ++------------ cake/tests/cases/libs/view/helpers/text.test.php | 10 ++++++++-- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/cake/libs/view/helpers/text.php b/cake/libs/view/helpers/text.php index 00ba9b2b195..0f4c490e1df 100644 --- a/cake/libs/view/helpers/text.php +++ b/cake/libs/view/helpers/text.php @@ -331,18 +331,8 @@ function excerpt($text, $phrase, $radius = 100, $ending = '...') { * @return string * @access public */ - function toList($list, $and = 'and') { - $return = ''; - $count = count($list) - 1; - $counter = 0; - foreach ($list as $i => $item) { - $return .= $item; - if ($count > 0 && $counter < $count) { - $return .= ($counter < $count - 1 ? ', ' : " {$and} "); - } - $counter++; - } - return $return; + function toList($list, $and = 'and', $separator = ', ') { + return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop(array_slice($list, -1)); } } ?> \ No newline at end of file diff --git a/cake/tests/cases/libs/view/helpers/text.test.php b/cake/tests/cases/libs/view/helpers/text.test.php index a9c9ba63d71..84dcbf9e449 100644 --- a/cake/tests/cases/libs/view/helpers/text.test.php +++ b/cake/tests/cases/libs/view/helpers/text.test.php @@ -363,8 +363,14 @@ function testListGeneration() { $result = $this->Text->toList(array('Dusty', 'Lucky', 'Ned'), 'y'); $this->assertEqual($result, 'Dusty, Lucky y Ned'); - $result = $this->Text->toList(array( 1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'y'); - $this->assertEqual($result, 'Dusty, Lucky y Ned'); + $result = $this->Text->toList(array( 1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'y'); + $this->assertEqual($result, 'Dusty, Lucky y Ned'); + + $result = $this->Text->toList(array( 1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'and', ' + '); + $this->assertEqual($result, 'Dusty + Lucky and Ned'); + + $result = $this->Text->toList(array( 'name1' => 'Dusty', 'name2' => 'Lucky')); + $this->assertEqual($result, 'Dusty and Lucky'); } } ?> \ No newline at end of file