You are here

BadgeAccessCheck.php in User Badges 8

File

src/Access/BadgeAccessCheck.php
View source
<?php

namespace Drupal\user_badges\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Defines the access control handler for the badge listing.
 */
class BadgeAccessCheck implements AccessInterface {

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs the access check.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * Checks access to the badge listing pages.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The currently logged in account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    $badge_admin = $account
      ->hasPermission('administer badge entities');
    if ($badge_admin) {
      return AccessResult::allowed();
    }
    else {
      $user_from_url = $this->routeMatch
        ->getParameter('user');

      // GetParameter returns the entity and sometimes returns a string.
      if (!is_string($user_from_url)) {
        $user_from_url = $user_from_url
          ->id();
      }
      return AccessResult::allowedIf($account
        ->id() && $account
        ->id() == $user_from_url && $account
        ->hasPermission('re-order badges'))
        ->cachePerPermissions()
        ->cachePerUser();
    }
  }

}

Classes

Namesort descending Description
BadgeAccessCheck Defines the access control handler for the badge listing.