<?php

namespace Drupal\nodehive_core;

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

/**
 * Defines the access control handler for the space entity type.
 */
class SpaceAccessControlHandler extends EntityAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    if (in_array("administrator", $account->getRoles()) || $account->id() == 1) {
      return AccessResult::allowed();
    }

    $editors_ids = [];
    $editors = $entity->editors->getValue();
    foreach ($editors as $item) {
      $editors_ids[] = $item['target_id'];
    }

    if (in_array($account->id(), $editors_ids)) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }

  /**
   * {@inheritdoc}
   */
  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
    return AccessResult::allowedIfHasPermissions(
      $account,
      ['create space'],
    );
  }

}
