<?php

declare(strict_types=1);

namespace Drupal\data_stream;

use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\data_stream\Attribute\DataStreamType;
use Drupal\data_stream\Plugin\DataStream\DataStreamType\DataStreamTypeInterface;

/**
 * Data Stream Type plugin manager.
 */
class DataStreamTypeManager extends DefaultPluginManager {

  public function __construct(
    \Traversable $namespaces,
    CacheBackendInterface $cache_backend,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct(
      'Plugin/DataStream/DataStreamType',
      $namespaces,
      $module_handler,
      DataStreamTypeInterface::class,
      DataStreamType::class,
      'Drupal\data_stream\Annotation\DataStreamType',
    );
    $this->alterInfo('data_stream_type_info');
    $this->setCacheBackend($cache_backend, 'data_stream_type_plugins');
  }

  /**
   * {@inheritdoc}
   */
  public function processDefinition(&$definition, $plugin_id) {
    parent::processDefinition($definition, $plugin_id);

    foreach (['id', 'label'] as $required_property) {
      if (empty($definition[$required_property])) {
        throw new PluginException(sprintf('The data stream type %s must define the %s property.', $plugin_id, $required_property));
      }
    }
  }

}
