Skip to content

Commit

Permalink
Merge pull request #53 from dereuromark/bugfix/multi-role-performance
Browse files Browse the repository at this point in the history
Cache DB queries for performance
  • Loading branch information
dereuromark authored Dec 20, 2016
2 parents 0ad81ef + a3782fe commit 13c5dc7
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/Auth/AclTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ trait AclTrait {
*/
protected $_roles = null;

/**
* @var array|null
*/
protected $_userRoles = null;

/**
* @return array
*/
Expand Down Expand Up @@ -380,20 +385,36 @@ protected function _getUserRoles($user) {
}

// Multi-role from DB: load the pivot table
$roles = $this->_getRolesFromDb($pivotTableName, $user[$this->_config['idColumn']]);
if (!$roles) {
return [];
}

return $this->_mapped($roles);
}

/**
* @param string $pivotTableName
* @param int $id User ID
* @return array
*/
protected function _getRolesFromDb($pivotTableName, $id) {
if (isset($this->_userRoles[$id])) {
return $this->_userRoles[$id];
}

$pivotTable = TableRegistry::get($pivotTableName);
$roleColumn = $this->_config['roleColumn'];
$roles = $pivotTable->find()
->select($roleColumn)
->where([$this->_config['userColumn'] => $user[$this->_config['idColumn']]])
->where([$this->_config['userColumn'] => $id])
->all()
->extract($roleColumn)
->toArray();

if (!count($roles)) {
return [];
}
$this->_userRoles[$id] = $roles;

return $this->_mapped($roles);
return $roles;
}

/**
Expand Down

0 comments on commit 13c5dc7

Please sign in to comment.