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->instanceId = $instance_id;
56 // This is still needed by the parent LazyPluginCollection class.
57 $this->instanceIDs = [$instance_id => $instance_id];
58 $this->configuration = $configuration;
64 protected function initializePlugin($instance_id) {
65 $this->set($instance_id, $this->manager->createInstance($instance_id, $this->configuration));
71 public function getConfiguration() {
72 $plugin = $this->get($this->instanceId);
73 if ($plugin instanceof ConfigurablePluginInterface) {
74 return $plugin->getConfiguration();
77 return $this->configuration;
84 public function setConfiguration($configuration) {
85 $this->configuration = $configuration;
86 $plugin = $this->get($this->instanceId);
87 if ($plugin instanceof ConfigurablePluginInterface) {
88 $plugin->setConfiguration($configuration);
96 public function addInstanceId($id, $configuration = NULL) {
97 $this->instanceId = $id;
98 parent::addInstanceId($id, $configuration);
99 if ($configuration !== NULL) {
100 $this->setConfiguration($configuration);