<?php

declare(strict_types=1);

namespace Drupal\farm_entity;

use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\farm_entity\Attribute\PlanRecordType;
use Drupal\farm_entity\Plugin\PlanRecord\PlanRecordType\PlanRecordTypeInterface;

/**
 * Plan Record Type plugin manager.
 */
class PlanRecordTypeManager extends DefaultPluginManager {

  public function __construct(
    \Traversable $namespaces,
    CacheBackendInterface $cache_backend,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct(
      'Plugin/PlanRecord/PlanRecordType',
      $namespaces,
      $module_handler,
      PlanRecordTypeInterface::class,
      PlanRecordType::class,
      'Drupal\farm_entity\Annotation\PlanRecordType',
    );
    $this->alterInfo('plan_record_type_info');
    $this->setCacheBackend($cache_backend, 'plan_record_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 plan record relationship type %s must define the %s property.', $plugin_id, $required_property));
      }
    }
  }

}
