1<?php 2 3namespace Drupal\Component\Plugin\Discovery; 4 5use Drupal\Component\Plugin\Exception\PluginNotFoundException; 6 7/** 8 * @see Drupal\Component\Plugin\Discovery\DiscoveryInterface 9 */ 10trait DiscoveryTrait { 11 12 /** 13 * {@inheritdoc} 14 */ 15 abstract public function getDefinitions(); 16 17 /** 18 * {@inheritdoc} 19 */ 20 public function getDefinition($plugin_id, $exception_on_invalid = TRUE) { 21 $definitions = $this->getDefinitions(); 22 return $this->doGetDefinition($definitions, $plugin_id, $exception_on_invalid); 23 } 24 25 /** 26 * Gets a specific plugin definition. 27 * 28 * @param array $definitions 29 * An array of the available plugin definitions. 30 * @param string $plugin_id 31 * A plugin id. 32 * @param bool $exception_on_invalid 33 * If TRUE, an invalid plugin ID will cause an exception to be thrown; if 34 * FALSE, NULL will be returned. 35 * 36 * @return array|null 37 * A plugin definition, or NULL if the plugin ID is invalid and 38 * $exception_on_invalid is TRUE. 39 * 40 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException 41 * Thrown if $plugin_id is invalid and $exception_on_invalid is TRUE. 42 */ 43 protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) { 44 // Avoid using a ternary that would create a copy of the array. 45 if (isset($definitions[$plugin_id])) { 46 return $definitions[$plugin_id]; 47 } 48 elseif (!$exception_on_invalid) { 49 return NULL; 50 } 51 52 $valid_ids = implode(', ', array_keys($definitions)); 53 throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist. Valid plugin IDs for %s are: %s', $plugin_id, static::class, $valid_ids)); 54 } 55 56 /** 57 * {@inheritdoc} 58 */ 59 public function hasDefinition($plugin_id) { 60 return (bool) $this->getDefinition($plugin_id, FALSE); 61 } 62 63} 64