EntityActionDeriverBase.php in Drupal 8
File
core/lib/Drupal/Core/Action/Plugin/Action/Derivative/EntityActionDeriverBase.php
View source
<?php
namespace Drupal\Core\Action\Plugin\Action\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class EntityActionDeriverBase extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->stringTranslation = $string_translation;
}
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static($container
->get('entity_type.manager'), $container
->get('string_translation'));
}
protected abstract function isApplicable(EntityTypeInterface $entity_type);
public function getDerivativeDefinitions($base_plugin_definition) {
if (empty($this->derivatives)) {
$definitions = [];
foreach ($this
->getApplicableEntityTypes() as $entity_type_id => $entity_type) {
$definition = $base_plugin_definition;
$definition['type'] = $entity_type_id;
$definition['label'] = sprintf('%s %s', $base_plugin_definition['action_label'], $entity_type
->getSingularLabel());
$definitions[$entity_type_id] = $definition;
}
$this->derivatives = $definitions;
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
protected function getApplicableEntityTypes() {
$entity_types = $this->entityTypeManager
->getDefinitions();
$entity_types = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
return $this
->isApplicable($entity_type);
});
return $entity_types;
}
}