Skip to content

Commit

Permalink
Merge pull request #29 from dereuromark/master
Browse files Browse the repository at this point in the history
Move entity to version code into behavior.
  • Loading branch information
josegonzalez authored Apr 20, 2017
2 parents 1a30771 + 84935f1 commit 4f0c098
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 17 deletions.
23 changes: 6 additions & 17 deletions src/Model/Behavior/Version/VersionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,13 @@ public function versions($reset = false)
return $this->get('_versions');
}

/*
* @var \Josegonzalez\Version\Model\Behavior\VersionBehavior $table
* @var \Cake\Datasource\EntityInterface $this
*/
$table = TableRegistry::get($this->source());
$primaryKey = (array)$table->primaryKey();

$query = $table->find('versions');
$pkValue = $this->extract($primaryKey);
$conditions = [];
foreach ($pkValue as $key => $value) {
$field = current($query->aliasField($key));
$conditions[$field] = $value;
}
$entities = $query->where($conditions)->all();

if (empty($entities)) {
return new Collection([]);
}

$entity = $entities->first();
$this->set('_versions', $entity->get('_versions'));
$versions = $table->getVersions($this);
$this->set('_versions', $versions);

return $this->get('_versions');
}
Expand Down
29 changes: 29 additions & 0 deletions src/Model/Behavior/VersionBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Cake\Event\Event;
use Cake\Event\EventManager;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
Expand Down Expand Up @@ -326,6 +327,34 @@ public function groupVersions($results)
});
}

/**
* Returns the versions of a specific entity.
*
* @param \Cake\Datasource\EntityInterface $entity Entity.
* @return \Cake\Collection\CollectionInterface
*/
public function getVersions(EntityInterface $entity)
{
$primaryKey = (array)$this->_table->primaryKey();

$query = $this->_table->find('versions');
$pkValue = $entity->extract($primaryKey);
$conditions = [];
foreach ($pkValue as $key => $value) {
$field = current($query->aliasField($key));
$conditions[$field] = $value;
}
$entities = $query->where($conditions)->all();

if (empty($entities)) {
return new Collection([]);
}

$entity = $entities->first();

return $entity->get('_versions');
}

/**
* Returns an array of fields to be versioned.
*
Expand Down

0 comments on commit 4f0c098

Please sign in to comment.