l10n_server-2.x-dev/l10n_community/src/L10nAccess.php
l10n_community/src/L10nAccess.php
<?php declare(strict_types=1); namespace Drupal\l10n_community; use Drupal\Core\Extension\ModuleHandler; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\group\Entity\Group; use Drupal\user\Entity\User; /** * Service description. */ class L10nAccess { /** * The current route match. * * @var \Drupal\Core\Routing\RouteMatchInterface */ protected RouteMatchInterface $routeMatch; /** * The module handler. * * @var \Drupal\Core\Extension\ModuleHandler */ protected ModuleHandler $moduleHandler; /** * Constructs a L10nAccess object. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The current route match. * @param \Drupal\Core\Extension\ModuleHandler $module_handler * The module handler. */ public function __construct( RouteMatchInterface $route_match, ModuleHandler $module_handler, ) { $this->routeMatch = $route_match; $this->moduleHandler = $module_handler; } /** * Check if a user has a permission (in the current group or globally). * * @param string $permission * Permission name. * @param \Drupal\user\Entity\User|null $account * (optional) User account object to check the permission against. * * @return bool * TRUE if the user has the $permission in the current group (if one is set) * or globally. * FALSE if the user does not have the permission neither in the * current group (if one is set) neither globally. */ public function check(string $permission, ?User $account = NULL) { $group_access = FALSE; if (!$account) { $account = \Drupal::currentUser()->getAccount(); } /** @var \Drupal\group\Entity\Group $group */ $group = $this->routeMatch->getParameter('group'); if (\Drupal::moduleHandler()->moduleExists('l10n_groups') && ($group instanceof Group)) { $group_access = $group->hasPermission($permission, $account); } return $group_access || $account->hasPermission($permission); } }