Commit: 60eee416abd5689a3c9816cddc28aeb4a84e360b
Author: Nate Abele | Date: 2010-03-08 10:37:37 -0500
diff --git a/libraries/lithium/tests/cases/util/CollectionTest.php b/libraries/lithium/tests/cases/util/CollectionTest.php
index eb12e70..7986256 100644
--- a/libraries/lithium/tests/cases/util/CollectionTest.php
+++ b/libraries/lithium/tests/cases/util/CollectionTest.php
@@ -222,6 +222,12 @@ class CollectionTest extends \lithium\test\Unit {
$this->assertEqual(array(0, 1, 'baz'), $collection->keys());
}
+ /**
+ * Tests that various types of handlers can be registered with `Collection::formats()`, and
+ * that collection instances are converted correctly.
+ *
+ * @return void
+ */
public function testCollectionFormatConversion() {
Collection::formats('\lithium\net\http\Media');
$items = array('hello', 'goodbye', 'foo' => array('bar', 'baz' => 'dib'));
@@ -229,9 +235,27 @@ class CollectionTest extends \lithium\test\Unit {
$expected = json_encode($items);
$result = $collection->to('json');
- $this->assertEqual($result, $expected);
+ $this->assertEqual($expected, $result);
$this->assertNull($collection->to('badness'));
+
+ Collection::formats(false);
+ $this->assertNull($collection->to('json'));
+
+ Collection::formats('json', function($collection, $options) {
+ return json_encode($collection->to('array'));
+ });
+ $result = $collection->to('json');
+ $this->assertEqual($expected, $result);
+
+ $result = $collection->to(function($collection) {
+ $value = array_map(
+ function($i) { return is_array($i) ? join(',', $i) : $i; }, $collection->to('array')
+ );
+ return join(',', $value);
+ });
+ $expected = 'hello,goodbye,bar,dib';
+ $this->assertEqual($expected, $result);
}
}
diff --git a/libraries/lithium/util/Collection.php b/libraries/lithium/util/Collection.php
index 2d23419..f0e7281 100644
--- a/libraries/lithium/util/Collection.php
+++ b/libraries/lithium/util/Collection.php
@@ -159,7 +159,7 @@ class Collection extends \lithium\core\Object implements \ArrayAccess, \Iterator
*/
public static function formats($format, $handler = null) {
if ($format === false) {
- return static::$_formats = array();
+ return static::$_formats = array('array' => '\lithium\util\Collection::_toArray');
}
if ((is_null($handler)) && class_exists($format)) {
return static::$_formats[] = $format;