<?php

namespace Drupal\nodehive_core\EventSubscriber;

use Drupal\entity\QueryAccess\QueryAccessEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber for nodehive_space query access.
 */
class QueryAccessSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      'entity.query_access.nodehive_space' => 'onQueryAccess',
    ];
  }

  /**
   * Modifies the access conditions based on the current user.
   */
  public function onQueryAccess(QueryAccessEvent $event) {
    $conditions = $event->getConditions();
    $account = $event->getAccount();

    $is_current_user_admin = FALSE;
    if (
      in_array("administrator", $account->getRoles()) ||
      in_array("nodehive_content_admin", $account->getRoles()) ||
      $account->id() == 1
    ) {
      $is_current_user_admin = TRUE;
    }

    if (!$is_current_user_admin) {
      $conditions->addCondition("editors", $account->id(), "IN");
    }
  }

}
