You are here

public function AgreementHandler::getAgreementByUserAndPath in Agreement 8.2

Same name and namespace in other branches
  1. 3.0.x src/AgreementHandler.php \Drupal\agreement\AgreementHandler::getAgreementByUserAndPath()

Find the agreement by user account and path.

Parameters

\Drupal\Core\Session\AccountProxyInterface $account: The user account to check.

string $path: The path to check.

Return value

\Drupal\agreement\Entity\Agreement|false The agreement entity to use or FALSE if none found.

Overrides AgreementHandlerInterface::getAgreementByUserAndPath

File

src/AgreementHandler.php, line 140

Class

AgreementHandler
Agreement handler provides methods for looking up agreements.

Namespace

Drupal\agreement

Code

public function getAgreementByUserAndPath(AccountProxyInterface $account, $path) {
  $agreement_types = $this->entityTypeManager
    ->getStorage('agreement')
    ->loadMultiple();
  $default_exceptions = [
    '/user/password',
    '/user/register',
    '/user/reset/*',
    '/user/login',
    '/user/logout',
    '/admin/config/people/agreement',
    '/admin/config/people/agreement/*',
    '/admin/config/people/agreement/manage/*',
  ];

  // Get a list of pages to never display agreements on.
  $exceptions = array_reduce($agreement_types, function (&$result, Agreement $item) {
    $result[] = $item
      ->get('path');
    return $result;
  }, $default_exceptions);
  $exception_string = implode("\n", $exceptions);
  if ($this->pathMatcher
    ->matchPath($path, $exception_string)) {
    return FALSE;
  }

  // Reduce the agreement types based on the user role.
  $agreements_with_roles = array_reduce($agreement_types, function (&$result, Agreement $item) use ($account) {
    if ($item
      ->accountHasAgreementRole($account)) {
      $result[] = $item;
    }
    return $result;
  }, []);

  // Try to find an agreement type that matches the path.
  $pathMatcher = $this->pathMatcher;
  $self = $this;
  $info = array_reduce($agreements_with_roles, function (&$result, Agreement $item) use ($account, $path, $pathMatcher, $self) {
    if ($result) {

      // Always returns the first matched agreement.
      return $result;
    }
    $pattern = $item
      ->getVisibilityPages();
    $has_match = $pathMatcher
      ->matchPath($path, $pattern);
    $has_agreed = $self
      ->hasAgreed($item, $account);
    $visibility = (int) $item
      ->getVisibilitySetting();
    if (0 === $visibility && FALSE === $has_match && !$has_agreed) {

      // An agreement exists that matches any page.
      $result = $item;
    }
    elseif (1 === $visibility && $has_match && !$has_agreed) {

      // An agreement exists that matches the current path.
      $result = $item;
    }
    return $result;
  }, FALSE);
  return $info;
}