Mercurial > hg > isophonics-drupal-site
diff core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php @ 0:4c8ae668cc8c
Initial import (non-working)
author | Chris Cannam |
---|---|
date | Wed, 29 Nov 2017 16:09:58 +0000 |
parents | |
children | af1871eacc83 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php Wed Nov 29 16:09:58 2017 +0000 @@ -0,0 +1,62 @@ +<?php + +namespace Drupal\Component\Plugin\Discovery; + +use Drupal\Component\Plugin\Exception\PluginNotFoundException; + +/** + * @see Drupal\Component\Plugin\Discovery\DiscoveryInterface + */ +trait DiscoveryTrait { + + /** + * {@inheritdoc} + */ + abstract public function getDefinitions(); + + /** + * {@inheritdoc} + */ + public function getDefinition($plugin_id, $exception_on_invalid = TRUE) { + $definitions = $this->getDefinitions(); + return $this->doGetDefinition($definitions, $plugin_id, $exception_on_invalid); + } + + /** + * Gets a specific plugin definition. + * + * @param array $definitions + * An array of the available plugin definitions. + * @param string $plugin_id + * A plugin id. + * @param bool $exception_on_invalid + * If TRUE, an invalid plugin ID will cause an exception to be thrown; if + * FALSE, NULL will be returned. + * + * @return array|null + * A plugin definition, or NULL if the plugin ID is invalid and + * $exception_on_invalid is TRUE. + * + * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException + * Thrown if $plugin_id is invalid and $exception_on_invalid is TRUE. + */ + protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) { + // Avoid using a ternary that would create a copy of the array. + if (isset($definitions[$plugin_id])) { + return $definitions[$plugin_id]; + } + elseif (!$exception_on_invalid) { + return NULL; + } + + throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id)); + } + + /** + * {@inheritdoc} + */ + public function hasDefinition($plugin_id) { + return (bool) $this->getDefinition($plugin_id, FALSE); + } + +}