Allows MongoIds and MongoDates in arrays of subobjects. #629

Closed
wants to merge 1 commit into
from
View
22 data/source/mongo_db/Exporter.php
@@ -76,6 +76,9 @@ protected static function _cast($value, $def, $database, $options) {
$isArray = (is_array($value) && $def['array'] !== false && !$isObject);
$isArray = $def['array'] || $isArray;
+ if (!empty($def['null']) && ($value === null || $value === "")) {
+ return null;
+ }
if (isset($options['handlers'][$type]) && $handler = $options['handlers'][$type]) {
$value = $isArray ? array_map($handler, (array) $value) : $handler($value);
}
@@ -173,12 +176,21 @@ protected static function _update($export) {
foreach ($data as $key => $value) {
$original = $export['data'];
$isArray = is_object($value) && get_class($value) == static::$_classes['array'];
- if ($isArray && isset($original[$key]) && $value->data() != $original[$key]->data()) {
- $value = $value->data();
- }
- if ($isArray && !isset($original[$key])) {
- $value = $value->data();
+ $options = array('handlers' => array(
+ 'MongoDate' => function($value) { return $value; },
+ 'MongoId' => function($value) { return $value; }
+ ));
+ if ($isArray) {
+ $newValue = $value->to('array', $options);
+ $originalValue = null;
+ if (isset($original[$key])) {
+ $originalValue = $original[$key]->to('array', $options);
+ }
+ if ($newValue !== $originalValue) {
+ $value = $value->to('array', $options);
+ }
}
+
$result = static::_append($result, "{$path}{$key}", $value, 'update');
}
return array_filter($result);
View
27 tests/cases/util/CollectionTest.php
@@ -275,6 +275,33 @@ function($i) { return is_array($i) ? join(',', $i) : $i; }, $collection->to('arr
$this->assertEqual($expected, $result);
}
+ public function testCollectionHandlers() {
+ $obj = new StdClass();
+ $obj->a = "b";
+ $handlers = array(
+ 'stdClass' => function($v) { return (array) $v; }
+ );
+ $data = array(
+ 'test' => new Collection(array('data' => compact('obj'))),
+ 'obj' => $obj
+ );
+
+ $collection = new Collection(compact('data'));
+ $expected = array(
+ 'test' => array(
+ 'obj' => array('a' => 'b')
+ ),
+ 'obj' => array('a' => 'b')
+ );
+ $this->assertIdentical($expected, $collection->to('array', compact('handlers')));
+
+ $handlers = array(
+ 'stdClass' => function($v) { return $v; }
+ );
+ $expected = array('test' => compact('obj')) + compact('obj');
+ $this->assertIdentical($expected, $collection->to('array', compact('handlers')));
+ }
+
/**
* Tests that the Collection::sort method works appropriately.
*
View
2 util/Collection.php
@@ -556,7 +556,7 @@ public static function toArray($data, array $options = array()) {
$result[$key] = $options['handlers'][$class]($item);
break;
case (method_exists($item, 'to')):
- $result[$key] = $item->to('array');
+ $result[$key] = $item->to('array', $options);
break;
case ($vars = get_object_vars($item)):
$result[$key] = static::toArray($vars, $options);