<?php

namespace Drupal\nodehive_area_fragment;

use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Access controller for the nodehive area entity.
 */
class AreaAccessControlHandler extends EntityAccessControlHandler {

  /**
   * The entity id.
   *
   * @var string
   */
  public static $name = 'nodehive_area';

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    /** @var \Drupal\nodehive_area_fragment\AreaInterface $entity */
    $admin_permission = $this->entityType->getAdminPermission();
    if ($account->hasPermission($admin_permission)) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    if (
      $entity->isPublished() &&
      $account->hasPermission('view published nodehive area')
    ) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    if (
      !$entity->isPublished() &&
      $account->hasPermission('view unpublished nodehive area')
    ) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    return AccessResult::allowedIfHasPermission(
      $account,
      'view published nodehive area'
    );
  }

}
