<?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 fragment entity.
 */
class FragmentAccessControlHandler extends EntityAccessControlHandler {

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

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

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

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

    return AccessResult::allowedIfHasPermission(
      $account,
      'administer nodehive fragment'
    );
  }

}
