From a7b86faadf776fb1871dd9fbec197703d4e58333 Mon Sep 17 00:00:00 2001 From: jackbravo Date: Mon, 26 Nov 2007 22:52:36 +0000 Subject: [PATCH] Added mergeDeep method to Doctrine_Record. Be carefull when using it as it loads related records. But can be really convenient, specially when loading data from the _GET and _POST variables (possibly from a form) --- lib/Doctrine/Record.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/lib/Doctrine/Record.php b/lib/Doctrine/Record.php index a46e6982e..25efd86a4 100644 --- a/lib/Doctrine/Record.php +++ b/lib/Doctrine/Record.php @@ -1492,6 +1492,46 @@ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Count } } + /** + * mergeDeep + * merges this record with an array of values + * + * @pre it is expected that the array keys representing a hasMany + * relationship are the keyColumn set with INDEXBY + * + * @param array $values + * @param $rmFromCollection if some records are not found in the array, + * they are removed from the collection<->relation + * @return void + */ + public function mergeDeep(array $values, $rmFromCollection = false) + { + $this->merge($values); + + foreach ($values as $rel_name => $rel_data) { + if ($this->getTable()->hasRelation($rel_name)) { + $rel = $this->get($rel_name); + if ($rel instanceof Doctrine_Collection) { + foreach ($rel as $key => $record) { + if (isset($rel_data[$key])) { + $record->mergeDeep($rel_data[$key], $rmFromCollection); + unset($rel_data[$key]); + } elseif ($rmFromCollection) { + $rel->remove($key); + } + } + foreach ($rel_data as $key => $new_data) { + $new_record = $rel->getTable()->create(); + $new_record->mergeDeep($new_data); + $rel->add($new_record, $key); + } + } else { + $rel->mergeDeep($rel_data); + } + } + } + } + /** * call *