<?php

namespace Drupal\acquia_contenthub\EventSubscriber\ImportFailure;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\FailedImportEvent;
use Drupal\acquia_contenthub_subscriber\Exception\ContentHubImportException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Default exceptions for import failures.
 *
 * @package Drupal\acquia_contenthub\EventSubscriber\ImportFailure
 */
class DefaultException implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::IMPORT_FAILURE][] = 'onImportFailure';
    return $events;
  }

  /**
   * A default failure exception creator.
   *
   * @param \Drupal\acquia_contenthub\Event\FailedImportEvent $event
   *   The failure event.
   */
  public function onImportFailure(FailedImportEvent $event) {
    if (!$event->hasException()) {
      $exception = new ContentHubImportException(
        sprintf("Failed to import. %d of %d imported", $event->getCount(), count($event->getCdf()->getEntities())),
        ContentHubImportException::PARTIAL_IMPORT,
      );
      $event->setException($exception);
    }
  }

}
