Skip to content

Commit

Permalink
Expose preexistent logic in public function getVersionId
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Bouland committed May 5, 2017
1 parent 4f0c098 commit 5542910
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions src/Model/Behavior/VersionBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,49 +167,36 @@ public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $o
$fields = $this->_fields();
$values = $entity->extract($fields, $this->_config['onlyDirty']);

$model = $this->_config['referenceName'];
$primaryKey = (array)$this->_table->primaryKey();
$foreignKey = $this->_extractForeignKey($entity);
$versionField = $this->_config['versionField'];

if (isset($options['versionId'])) {
$versionId = $options['versionId'];
} else {
$table = TableRegistry::get($this->_config['versionTable']);
$preexistent = $table->find()
->select(['version_id'])
->where([
'model' => $model
] + $foreignKey)
->order(['id desc'])
->limit(1)
->hydrate(false)
->toArray();

$versionId = Hash::get($preexistent, '0.version_id', 0) + 1;
$versionId = $this->getVersionId($entity) + 1;
}
$created = new DateTime();
$new = [];
$entityClass = TableRegistry::get($this->_config['versionTable'])->entityClass();
foreach ($values as $field => $content) {
if (in_array($field, $primaryKey) || $field == $versionField) {
continue;
}

$data = [
'version_id' => $versionId,
'model' => $model,
'model' => $this->_config['referenceName'],
'field' => $field,
'content' => $content,
'created' => $created,
] + $foreignKey;
] + $this->_extractForeignKey($entity);

$event = new Event('Model.Version.beforeSave', $this, $options);
$userData = EventManager::instance()->dispatch($event);
if (isset($userData->result) && is_array($userData->result)) {
$data = array_merge($data, $userData->result);
}

$entityClass = $table->entityClass();
$new[$field] = new $entityClass($data, [
'useSetters' => false,
'markNew' => true
Expand All @@ -235,6 +222,28 @@ public function afterSave(Event $event, EntityInterface $entity)
$entity->unsetProperty($property);
}

/**
* return the last version id
*
* @param \Cake\Datasource\EntityInterface $entity Entity.
* @return int
*/
public function getVersionId(EntityInterface $entity)
{
$table = TableRegistry::get($this->_config['versionTable']);
$preexistent = $table->find()
->select(['version_id'])
->where([
'model' => $this->_config['referenceName']
] + $this->_extractForeignKey($entity))
->order(['id desc'])
->limit(1)
->hydrate(false)
->toArray();

return Hash::get($preexistent, '0.version_id', 0);
}

/**
* Custom finder method used to retrieve all versions for the found records.
*
Expand Down

0 comments on commit 5542910

Please sign in to comment.