3 namespace Drupal\Core\Plugin;
5 use Drupal\Component\Plugin\PluginManagerInterface;
6 use Drupal\Component\Plugin\LazyPluginCollection;
7 use Drupal\Component\Plugin\ConfigurablePluginInterface;
8 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
11 * Provides a default plugin collection for a plugin type.
13 * A plugin collection usually stores multiple plugins, and is used to lazily
14 * instantiate them. When only one plugin is needed, it is still best practice
15 * to encapsulate all of the instantiation logic in a plugin collection. This
16 * class can be used directly, or subclassed to add further exception handling
17 * in self::initializePlugin().
19 class DefaultSingleLazyPluginCollection extends LazyPluginCollection {
20 use DependencySerializationTrait;
23 * The manager used to instantiate the plugins.
25 * @var \Drupal\Component\Plugin\PluginManagerInterface
30 * An array of configuration to instantiate the plugin with.
34 protected $configuration;
37 * The instance ID used for this plugin collection.
41 protected $instanceId;
44 * Constructs a new DefaultSingleLazyPluginCollection object.
46 * @param \Drupal\Component\Plugin\PluginManagerInterface $manager
47 * The manager to be used for instantiating plugins.
48 * @param string $instance_id
49 * The ID of the plugin instance.
50 * @param array $configuration
51 * An array of configuration.
53 public function __construct(PluginManagerInterface $manager, $instance_id, array $configuration) {
54 $this->manager = $manager;
55 $this->addInstanceId($instance_id, $configuration);
61 protected function initializePlugin($instance_id) {
62 $this->set($instance_id, $this->manager->createInstance($instance_id, $this->configuration));
68 public function getConfiguration() {
69 $plugin = $this->get($this->instanceId);
70 if ($plugin instanceof ConfigurablePluginInterface) {
71 return $plugin->getConfiguration();
74 return $this->configuration;
81 public function setConfiguration($configuration) {
82 $this->configuration = $configuration;
83 $plugin = $this->get($this->instanceId);
84 if ($plugin instanceof ConfigurablePluginInterface) {
85 $plugin->setConfiguration($configuration);
93 public function addInstanceId($id, $configuration = NULL) {
94 $this->instanceId = $id;
95 // Reset the list of instance IDs since there can be only one.
96 $this->instanceIDs = [];
97 parent::addInstanceId($id, $configuration);
98 if ($configuration !== NULL) {
99 $this->setConfiguration($configuration);