diff --git a/src/Model/Behavior/Version/VersionTrait.php b/src/Model/Behavior/Version/VersionTrait.php index e294ed0..1b36967 100644 --- a/src/Model/Behavior/Version/VersionTrait.php +++ b/src/Model/Behavior/Version/VersionTrait.php @@ -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'); } diff --git a/src/Model/Behavior/VersionBehavior.php b/src/Model/Behavior/VersionBehavior.php index 6d07888..bcb8554 100644 --- a/src/Model/Behavior/VersionBehavior.php +++ b/src/Model/Behavior/VersionBehavior.php @@ -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; @@ -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. *