You are here

protected function EntityField::blockAccess in Chaos Tool Suite (ctools) 8.3

Indicates whether the block should be shown.

Blocks with specific access checking should override this method rather than access(), in order to avoid repeating the handling of the $return_as_object argument.

Parameters

\Drupal\Core\Session\AccountInterface $account: The user session for which to check access.

Return value

\Drupal\Core\Access\AccessResult The access result.

Overrides BlockPluginTrait::blockAccess

See also

self::access()

File

modules/ctools_block/src/Plugin/Block/EntityField.php, line 156

Class

EntityField
Provides a block to a field on an entity.

Namespace

Drupal\ctools_block\Plugin\Block

Code

protected function blockAccess(AccountInterface $account) {

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  $entity = $this
    ->getContextValue('entity');

  // Make sure we have access to the entity.
  $access = $entity
    ->access('view', $account, TRUE);
  if ($access
    ->isAllowed()) {

    // Check that the entity in question has this field.
    if ($entity instanceof FieldableEntityInterface && $entity
      ->hasField($this->fieldName)) {

      // Check field access.
      $field_access = $this->entityTypeManager
        ->getAccessControlHandler($this->entityTypeId)
        ->fieldAccess('view', $this
        ->getFieldDefinition(), $account);
      if ($field_access) {

        // Build a renderable array for the field.
        $build = $entity
          ->get($this->fieldName)
          ->view($this->configuration['formatter']);

        // If there are actual renderable children, grant access.
        if (Element::children($build)) {
          return AccessResult::allowed();
        }
      }
    }

    // Entity doesn't have this field, so access is denied.
    return AccessResult::forbidden();
  }

  // If we don't have access to the entity, return the forbidden result.
  return $access;
}