TimeTrackingAccessControlHandler.php in Drupal PM (Project Management) 4.x
File
modules/pm_timetracking/src/TimeTrackingAccessControlHandler.php
View source
<?php
namespace Drupal\pm_timetracking;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
class TimeTrackingAccessControlHandler extends EntityAccessControlHandler {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
$permission = $this
->checkOwn($entity, $operation, $account);
if (!empty($permission)) {
return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'view time tracking entities');
case 'update':
$permission = $this
->checkOwn($entity, $operation, $account);
if (!empty($permission)) {
return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'edit time tracking entities');
case 'delete':
$permission = $this
->checkOwn($entity, $operation, $account);
if (!empty($permission)) {
return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'delete time tracking entities');
}
return AccessResult::neutral();
}
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermission($account, 'add time tracking entities');
}
protected function checkOwn(EntityInterface $entity, string $operation, AccountInterface $account) {
$uid = $entity
->getOwnerId();
$is_own = $account
->isAuthenticated() && $account
->id() == $uid;
if (!$is_own) {
return NULL;
}
$bundle = $entity
->bundle();
$ops = [
'create' => 'pm_time_tracking %bundle add own %bundle entities',
'view' => 'pm_time_tracking %bundle view own entities',
'update' => 'pm_time_tracking %bundle edit own entities',
'delete' => 'pm_time_tracking %bundle delete own entities',
];
$permission = strtr($ops[$operation], [
'%bundle' => $bundle,
]);
if ($account
->hasPermission($permission)) {
return $permission;
}
return NULL;
}
}