Merge pull request #999 from dogmatic69/model-simplify

Simplify some model code
This commit is contained in:
Mark Story 2012-12-05 18:18:50 -08:00
commit 00d178fa28

View file

@ -1234,72 +1234,74 @@ class Model extends Object implements CakeEventListener {
$type = $this->getColumnType($field); $type = $this->getColumnType($field);
if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { if (!in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
$useNewDate = (isset($data['year']) || isset($data['month']) || return $data;
isset($data['day']) || isset($data['hour']) || isset($data['minute'])); }
$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); $useNewDate = (isset($data['year']) || isset($data['month']) ||
$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); isset($data['day']) || isset($data['hour']) || isset($data['minute']));
$date = array();
if (isset($data['meridian']) && empty($data['meridian'])) { $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
return null; $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
} $date = array();
if ( if (isset($data['meridian']) && empty($data['meridian'])) {
isset($data['hour']) && return null;
isset($data['meridian']) && }
!empty($data['hour']) &&
$data['hour'] != 12 && if (
'pm' == $data['meridian'] isset($data['hour']) &&
) { isset($data['meridian']) &&
$data['hour'] = $data['hour'] + 12; !empty($data['hour']) &&
$data['hour'] != 12 &&
'pm' == $data['meridian']
) {
$data['hour'] = $data['hour'] + 12;
}
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
$data['hour'] = '00';
}
if ($type == 'time') {
foreach ($timeFields as $key => $val) {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00';
} elseif ($data[$val] !== '') {
$data[$val] = sprintf('%02d', $data[$val]);
}
if (!empty($data[$val])) {
$date[$key] = $data[$val];
} else {
return null;
}
} }
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { }
$data['hour'] = '00';
} if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
if ($type == 'time') { foreach ($dateFields as $key => $val) {
foreach ($timeFields as $key => $val) { if ($val == 'hour' || $val == 'min' || $val == 'sec') {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00'; $data[$val] = '00';
} elseif ($data[$val] !== '') { } else {
$data[$val] = sprintf('%02d', $data[$val]); $data[$val] = sprintf('%02d', $data[$val]);
} }
if (!empty($data[$val])) { }
$date[$key] = $data[$val]; if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
} else { return null;
return null; }
} if (isset($data[$val]) && !empty($data[$val])) {
$date[$key] = $data[$val];
} }
} }
}
if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') { if ($useNewDate && !empty($date)) {
foreach ($dateFields as $key => $val) { $format = $this->getDataSource()->columns[$type]['format'];
if ($val == 'hour' || $val == 'min' || $val == 'sec') { foreach (array('m', 'd', 'H', 'i', 's') as $index) {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { if (isset($date[$index])) {
$data[$val] = '00'; $date[$index] = sprintf('%02d', $date[$index]);
} else {
$data[$val] = sprintf('%02d', $data[$val]);
}
}
if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
return null;
}
if (isset($data[$val]) && !empty($data[$val])) {
$date[$key] = $data[$val];
}
} }
} }
return str_replace(array_keys($date), array_values($date), $format);
if ($useNewDate && !empty($date)) {
$format = $this->getDataSource()->columns[$type]['format'];
foreach (array('m', 'd', 'H', 'i', 's') as $index) {
if (isset($date[$index])) {
$date[$index] = sprintf('%02d', $date[$index]);
}
}
return str_replace(array_keys($date), array_values($date), $format);
}
} }
return $data; return $data;
} }
@ -1321,14 +1323,13 @@ class Model extends Object implements CakeEventListener {
$this->_schema = array(); $this->_schema = array();
} }
} }
if (is_string($field)) { if (!is_string($field)) {
if (isset($this->_schema[$field])) { return $this->_schema;
return $this->_schema[$field];
} else {
return null;
}
} }
return $this->_schema; if (isset($this->_schema[$field])) {
return $this->_schema[$field];
}
return null;
} }
/** /**
@ -1394,10 +1395,8 @@ class Model extends Object implements CakeEventListener {
return false; return false;
} }
if ($checkVirtual && !empty($this->virtualFields)) { if ($checkVirtual && !empty($this->virtualFields) && $this->isVirtualField($name)) {
if ($this->isVirtualField($name)) { return true;
return true;
}
} }
if (empty($this->_schema)) { if (empty($this->_schema)) {
@ -1421,10 +1420,7 @@ class Model extends Object implements CakeEventListener {
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
return true; return true;
} }
if ($this->Behaviors->hasMethod($method)) { return $this->Behaviors->hasMethod($method);
return true;
}
return false;
} }
/** /**
@ -1463,7 +1459,7 @@ class Model extends Object implements CakeEventListener {
} }
if ($this->isVirtualField($field)) { if ($this->isVirtualField($field)) {
if (strpos($field, '.') !== false) { if (strpos($field, '.') !== false) {
list($model, $field) = explode('.', $field); list(, $field) = pluginSplit($field);
} }
return $this->virtualFields[$field]; return $this->virtualFields[$field];
} }
@ -1548,28 +1544,27 @@ class Model extends Object implements CakeEventListener {
if ($conditions === null && $this->id !== false) { if ($conditions === null && $this->id !== false) {
$conditions = array($this->alias . '.' . $this->primaryKey => $this->id); $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
} }
$recursive = $this->recursive;
if ($this->recursive >= 1) { if ($this->recursive >= 1) {
$recursive = -1; $recursive = -1;
} else {
$recursive = $this->recursive;
} }
$fields = $name; $fields = $name;
if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) { $data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'));
if (strpos($name, '.') === false) { if (!$data) {
if (isset($data[$this->alias][$name])) { return false;
return $data[$this->alias][$name]; }
} if (strpos($name, '.') === false) {
} else { if (isset($data[$this->alias][$name])) {
$name = explode('.', $name); return $data[$this->alias][$name];
if (isset($data[$name[0]][$name[1]])) {
return $data[$name[0]][$name[1]];
}
}
if (isset($data[0]) && count($data[0]) > 0) {
return array_shift($data[0]);
} }
} else { } else {
return false; $name = explode('.', $name);
if (isset($data[$name[0]][$name[1]])) {
return $data[$name[0]][$name[1]];
}
}
if (isset($data[0]) && count($data[0]) > 0) {
return array_shift($data[0]);
} }
} }
@ -1588,10 +1583,9 @@ class Model extends Object implements CakeEventListener {
$id = $this->id; $id = $this->id;
$this->create(false); $this->create(false);
$options = array('validate' => $validate, 'fieldList' => array($name));
if (is_array($validate)) { if (is_array($validate)) {
$options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate); $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
} else {
$options = array('validate' => $validate, 'fieldList' => array($name));
} }
return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options); return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
} }
@ -1620,10 +1614,9 @@ class Model extends Object implements CakeEventListener {
} }
if (!empty($options['fieldList'])) { if (!empty($options['fieldList'])) {
$this->whitelist = $options['fieldList'];
if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) { if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
$this->whitelist = $options['fieldList'][$this->alias]; $this->whitelist = $options['fieldList'][$this->alias];
} else {
$this->whitelist = $options['fieldList'];
} }
} elseif ($options['fieldList'] === null) { } elseif ($options['fieldList'] === null) {
$this->whitelist = array(); $this->whitelist = array();
@ -1742,7 +1735,7 @@ class Model extends Object implements CakeEventListener {
} }
if (!$db->create($this, $fields, $values)) { if (!$db->create($this, $fields, $values)) {
$success = $created = false; $success = false;
} else { } else {
$created = true; $created = true;
} }
@ -2121,9 +2114,8 @@ class Model extends Object implements CakeEventListener {
if ($validates) { if ($validates) {
if ($transactionBegun) { if ($transactionBegun) {
return $db->commit() !== false; return $db->commit() !== false;
} else {
return true;
} }
return true;
} }
$db->rollback(); $db->rollback();
return false; return false;
@ -2306,9 +2298,8 @@ class Model extends Object implements CakeEventListener {
if ($validates) { if ($validates) {
if ($transactionBegun) { if ($transactionBegun) {
return $db->commit() !== false; return $db->commit() !== false;
} else {
return true;
} }
return true;
} }
$db->rollback(); $db->rollback();
return false; return false;
@ -2390,45 +2381,44 @@ class Model extends Object implements CakeEventListener {
$event = new CakeEvent('Model.beforeDelete', $this, array($cascade)); $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
list($event->break, $event->breakOn) = array(true, array(false, null)); list($event->break, $event->breakOn) = array(true, array(false, null));
$this->getEventManager()->dispatch($event); $this->getEventManager()->dispatch($event);
if (!$event->isStopped()) { if ($event->isStopped()) {
if (!$this->exists()) { return false;
return false; }
} if (!$this->exists()) {
$db = $this->getDataSource(); return false;
}
$this->_deleteDependent($id, $cascade); $this->_deleteDependent($id, $cascade);
$this->_deleteLinks($id); $this->_deleteLinks($id);
$this->id = $id; $this->id = $id;
$updateCounterCache = false; if (!empty($this->belongsTo)) {
if (!empty($this->belongsTo)) { foreach ($this->belongsTo as $assoc) {
foreach ($this->belongsTo as $assoc) { if (empty($assoc['counterCache'])) {
if (!empty($assoc['counterCache'])) { continue;
$updateCounterCache = true;
break;
}
} }
if ($updateCounterCache) {
$keys = $this->find('first', array(
'fields' => $this->_collectForeignKeys(),
'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
'recursive' => -1,
'callbacks' => false
));
}
}
if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) { $keys = $this->find('first', array(
if ($updateCounterCache) { 'fields' => $this->_collectForeignKeys(),
$this->updateCounterCache($keys[$this->alias]); 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
} 'recursive' => -1,
$this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this)); 'callbacks' => false
$this->_clearCache(); ));
$this->id = false; break;
return true;
} }
} }
return false;
if (!$this->getDataSource()->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
return false;
}
if (!empty($keys[$this->alias])) {
$this->updateCounterCache($keys[$this->alias]);
}
$this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
$this->_clearCache();
$this->id = false;
return true;
} }
/** /**
@ -2439,39 +2429,42 @@ class Model extends Object implements CakeEventListener {
* @return void * @return void
*/ */
protected function _deleteDependent($id, $cascade) { protected function _deleteDependent($id, $cascade) {
if ($cascade !== true) {
return;
}
if (!empty($this->__backAssociation)) { if (!empty($this->__backAssociation)) {
$savedAssociatons = $this->__backAssociation; $savedAssociatons = $this->__backAssociation;
$this->__backAssociation = array(); $this->__backAssociation = array();
} }
if ($cascade === true) {
foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
if ($data['dependent'] === true) {
$model = $this->{$assoc}; foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
if ($data['dependent'] !== true) {
continue;
}
if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) { $model = $this->{$assoc};
$model->recursive = 0;
$conditions = array($this->escapeField(null, $this->name) => $id);
} else {
$model->recursive = -1;
$conditions = array($model->escapeField($data['foreignKey']) => $id);
if ($data['conditions']) {
$conditions = array_merge((array)$data['conditions'], $conditions);
}
}
if (isset($data['exclusive']) && $data['exclusive']) { if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
$model->deleteAll($conditions); $model->recursive = 0;
} else { $conditions = array($this->escapeField(null, $this->name) => $id);
$records = $model->find('all', array( } else {
'conditions' => $conditions, 'fields' => $model->primaryKey $model->recursive = -1;
)); $conditions = array($model->escapeField($data['foreignKey']) => $id);
if ($data['conditions']) {
$conditions = array_merge((array)$data['conditions'], $conditions);
}
}
if (!empty($records)) { if (isset($data['exclusive']) && $data['exclusive']) {
foreach ($records as $record) { $model->deleteAll($conditions);
$model->delete($record[$model->alias][$model->primaryKey]); } else {
} $records = $model->find('all', array(
} 'conditions' => $conditions, 'fields' => $model->primaryKey
));
if (!empty($records)) {
foreach ($records as $record) {
$model->delete($record[$model->alias][$model->primaryKey]);
} }
} }
} }
@ -2489,7 +2482,7 @@ class Model extends Object implements CakeEventListener {
*/ */
protected function _deleteLinks($id) { protected function _deleteLinks($id) {
foreach ($this->hasAndBelongsToMany as $data) { foreach ($this->hasAndBelongsToMany as $data) {
list($plugin, $joinModel) = pluginSplit($data['with']); list(, $joinModel) = pluginSplit($data['with']);
$records = $this->{$joinModel}->find('all', array( $records = $this->{$joinModel}->find('all', array(
'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id), 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
'fields' => $this->{$joinModel}->primaryKey, 'fields' => $this->{$joinModel}->primaryKey,
@ -2521,38 +2514,37 @@ class Model extends Object implements CakeEventListener {
if (!$cascade && !$callbacks) { if (!$cascade && !$callbacks) {
return $db->delete($this, $conditions); return $db->delete($this, $conditions);
} else { }
$ids = $this->find('all', array_merge(array( $ids = $this->find('all', array_merge(array(
'fields' => "{$this->alias}.{$this->primaryKey}", 'fields' => "{$this->alias}.{$this->primaryKey}",
'recursive' => 0), compact('conditions')) 'recursive' => 0), compact('conditions'))
); );
if ($ids === false) { if ($ids === false) {
return false; return false;
} }
$ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}"); $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
if (empty($ids)) { if (empty($ids)) {
return true; return true;
} }
if ($callbacks) { if ($callbacks) {
$_id = $this->id; $_id = $this->id;
$result = true; $result = true;
foreach ($ids as $id) { foreach ($ids as $id) {
$result = ($result && $this->delete($id, $cascade)); $result = $result && $this->delete($id, $cascade);
} }
$this->id = $_id; $this->id = $_id;
return $result; return $result;
} else { }
foreach ($ids as $id) {
$this->_deleteLinks($id); foreach ($ids as $id) {
if ($cascade) { $this->_deleteLinks($id);
$this->_deleteDependent($id, $cascade); if ($cascade) {
} $this->_deleteDependent($id, $cascade);
}
return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
} }
} }
return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
} }
/** /**
@ -2589,9 +2581,13 @@ class Model extends Object implements CakeEventListener {
if ($id === false) { if ($id === false) {
return false; return false;
} }
$conditions = array($this->alias . '.' . $this->primaryKey => $id); return (bool)$this->find('count', array(
$query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false); 'conditions' => array(
return ($this->find('count', $query) > 0); $this->alias . '.' . $this->primaryKey => $id
),
'recursive' => -1,
'callbacks' => false
));
} }
/** /**
@ -2704,10 +2700,8 @@ class Model extends Object implements CakeEventListener {
(array)$query (array)$query
); );
if ($type !== 'all') { if ($type !== 'all' && $this->findMethods[$type] === true) {
if ($this->findMethods[$type] === true) { $query = $this->{'_find' . ucfirst($type)}('before', $query);
$query = $this->{'_find' . ucfirst($type)}('before', $query);
}
} }
if (!is_numeric($query['page']) || intval($query['page']) < 1) { if (!is_numeric($query['page']) || intval($query['page']) < 1) {
@ -2793,9 +2787,8 @@ class Model extends Object implements CakeEventListener {
if (isset($results[0][$key]['count'])) { if (isset($results[0][$key]['count'])) {
if ($query['group']) { if ($query['group']) {
return count($results); return count($results);
} else {
return intval($results[0][$key]['count']);
} }
return intval($results[0][$key]['count']);
} }
} }
return false; return false;
@ -2855,8 +2848,7 @@ class Model extends Object implements CakeEventListener {
if (empty($results)) { if (empty($results)) {
return array(); return array();
} }
$lst = $query['list']; return Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']);
return Hash::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
} }
} }
@ -3004,10 +2996,9 @@ class Model extends Object implements CakeEventListener {
unset($fields[$field]); unset($fields[$field]);
$field = $value; $field = $value;
$value = null;
if (isset($this->data[$this->alias][$field])) { if (isset($this->data[$this->alias][$field])) {
$value = $this->data[$this->alias][$field]; $value = $this->data[$this->alias][$field];
} else {
$value = null;
} }
} }
@ -3123,14 +3114,13 @@ class Model extends Object implements CakeEventListener {
if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) { if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
return false; return false;
} }
if (!is_array($this->id)) { if (!is_array($this->id)) {
return $this->id; return $this->id;
} }
if (isset($this->id[$list]) && !empty($this->id[$list])) { if (isset($this->id[$list]) && !empty($this->id[$list])) {
return $this->id[$list]; return $this->id[$list];
} elseif (isset($this->id[$list])) { }
if (isset($this->id[$list])) {
return false; return false;
} }
@ -3250,29 +3240,30 @@ class Model extends Object implements CakeEventListener {
} }
} }
return $associated; return $associated;
} elseif (in_array($type, $this->_associations)) { }
if (in_array($type, $this->_associations)) {
if (empty($this->{$type})) { if (empty($this->{$type})) {
return array(); return array();
} }
return array_keys($this->{$type}); return array_keys($this->{$type});
} else {
$assoc = array_merge(
$this->hasOne,
$this->hasMany,
$this->belongsTo,
$this->hasAndBelongsToMany
);
if (array_key_exists($type, $assoc)) {
foreach ($this->_associations as $a) {
if (isset($this->{$a}[$type])) {
$assoc[$type]['association'] = $a;
break;
}
}
return $assoc[$type];
}
return null;
} }
$assoc = array_merge(
$this->hasOne,
$this->hasMany,
$this->belongsTo,
$this->hasAndBelongsToMany
);
if (array_key_exists($type, $assoc)) {
foreach ($this->_associations as $a) {
if (isset($this->{$a}[$type])) {
$assoc[$type]['association'] = $a;
break;
}
}
return $assoc[$type];
}
return null;
} }
/** /**
@ -3287,7 +3278,8 @@ class Model extends Object implements CakeEventListener {
if (is_string($assoc)) { if (is_string($assoc)) {
list(, $assoc) = pluginSplit($assoc); list(, $assoc) = pluginSplit($assoc);
return array($assoc, array_keys($this->{$assoc}->schema())); return array($assoc, array_keys($this->{$assoc}->schema()));
} elseif (is_array($assoc)) { }
if (is_array($assoc)) {
$with = key($assoc); $with = key($assoc);
return array($with, array_unique(array_merge($assoc[$with], $keys))); return array($with, array_unique(array_merge($assoc[$with], $keys)));
} }