Example #1
0
 /**
  * Revert all rows matching conditions to given date.
  * Model rows outside condition or not edited will not be affected. Edits since date
  * will be reverted and rows created since date deleted.
  *
  * @param object $Model
  * @param array $options 'conditions','date'
  * @return boolean success
  */
 public function revertAll(Model $Model, $options = array())
 {
     if (!$Model->ShadowModel) {
         trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING);
         return false;
     }
     if (empty($options) || !isset($options['date'])) {
         return false;
     }
     if (!isset($options['conditions'])) {
         $options['conditions'] = array();
     }
     // leave model rows out side of condtions alone
     // leave model rows not edited since date alone
     $all = $Model->find('all', array('conditions' => $options['conditions'], 'fields' => $Model->primaryKey));
     $allIds = Set::extract($all, '/' . $Model->alias . '/' . $Model->primaryKey);
     $cond = $options['conditions'];
     $cond['version_created <'] = $options['date'];
     $created_before_date = $Model->ShadowModel->find('all', array('order' => $Model->primaryKey, 'conditions' => $cond, 'fields' => array('version_id', $Model->primaryKey)));
     $created_before_dateIds = Set::extract($created_before_date, '/' . $Model->alias . '/' . $Model->primaryKey);
     $deleteIds = array_diff($allIds, $created_before_dateIds);
     // delete all Model rows where there are only version_created later than date
     $Model->deleteAll(array($Model->alias . '.' . $Model->primaryKey => $deleteIds), false, true);
     unset($cond['version_created <']);
     $cond['version_created >='] = $options['date'];
     $created_after_date = $Model->ShadowModel->find('all', array('order' => $Model->primaryKey, 'conditions' => $cond, 'fields' => array('version_id', $Model->primaryKey)));
     $created_after_dateIds = Set::extract($created_after_date, '/' . $Model->alias . '/' . $Model->primaryKey);
     $updateIds = array_diff($created_after_dateIds, $deleteIds);
     $revertSuccess = true;
     // update model rows that have version_created earlier than date to latest before date
     foreach ($updateIds as $mid) {
         $Model->id = $mid;
         if (!$Model->revertToDate($options['date'])) {
             $revertSuccess = false;
         }
     }
     return $revertSuccess;
 }