<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\InvalidateDepcalcCache;

use Drupal\acquia_contenthub\PubSubModuleStatusChecker;
use Drupal\depcalc\DependencyCalculatorEvents;
use Drupal\depcalc\Event\InvalidateDepcalcCacheEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber to skip depcalc invalidation for subscriber only sites.
 */
class SkipDepcalcInvalidationOnSubscriberSites implements EventSubscriberInterface {

  /**
   * Checker service.
   *
   * @var \Drupal\acquia_contenthub\PubSubModuleStatusChecker
   */
  protected PubSubModuleStatusChecker $checker;

  /**
   * SkipTagInvalidationOnSubscriberSites constructor.
   *
   * @param \Drupal\acquia_contenthub\PubSubModuleStatusChecker $checker
   *   Checker service.
   */
  public function __construct(PubSubModuleStatusChecker $checker) {
    $this->checker = $checker;
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents(): array {
    $events[DependencyCalculatorEvents::INVALIDATE_DEPCALC_CACHE][] =
      ['skipDepcalcInvalidation', 1000];
    return $events;
  }

  /**
   * Skips tags invalidation for user entities.
   *
   * @param \Drupal\depcalc\Event\InvalidateDepcalcCacheEvent $event
   *   Invalidate tags event.
   */
  public function skipDepcalcInvalidation(InvalidateDepcalcCacheEvent $event): void {
    if ($this->checker->isPublisher()) {
      return;
    }
    // Don't invalidate depcalc cache if it's a subscriber site.
    $event->stopPropagation();
  }

}
