fieldry-1.0.x-dev/src/Plugin/FieldryWrapperManager.php
src/Plugin/FieldryWrapperManager.php
<?php
namespace Drupal\fieldry\Plugin;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\FormatterInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\fieldry\Attribute\FieldryWrapper;
use Drupal\fieldry\FieldDisplayInfo;
/**
* Plugin manager for discovering and creating FieldryWrapper plugins.
*/
class FieldryWrapperManager extends DefaultPluginManager implements FieldryWrapperManagerInterface {
/**
* Creates a new instance of display maestro field wrapper manager.
*
* @param \Traversable $namespaces
* A set of namespaces to traverse for item provider plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend to cache plugin definitions to.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* Module handler class for managing modules.
* @param \Drupal\fieldry\FieldDisplayInfo $fieldDisplayInfo
* Helper for fetching formatter settings for field displays.
*
* @see \Drupal\fieldry\Plugin\FieldWrapperManagerInterface::getByElement()
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, protected FieldDisplayInfo $fieldDisplayInfo) {
parent::__construct(
'Plugin/FieldryWrapper',
$namespaces,
$module_handler,
WrapperInterface::class,
FieldryWrapper::class
);
// Create plugin definition defaults.
$this->defaults['theme'] = 'fieldry_wrapper';
$this->alterInfo('fieldry_wrapper');
$this->setCacheBackend($cache_backend, 'fieldry_wrapper', ['fieldry_wrapper']);
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id): void {
if (empty($definition['theme'])) {
$definition['theme'] = 'fieldry_wrapper';
}
}
/**
* {@inheritdoc}
*/
public function getThemeHooks(): array {
$hooks = [];
foreach ($this->getDefinitions() as $def) {
$hooks[$def['theme']] = $def['theme'];
}
return $hooks;
}
/**
* {@inheritdoc}
*/
public function getFieldWrappers(FormatterInterface $formatter, FieldDefinitionInterface $field_definition): array {
$wrappers = [];
foreach ($this->getDefinitions() as $pluginDef) {
if ($pluginDef['class']::isApplicable($pluginDef, $formatter, $field_definition)) {
$wrappers[$pluginDef['id']] = $pluginDef['label'];
}
}
return $wrappers;
}
/**
* {@inheritdoc}
*/
public function getByElement(array $element): ?WrapperInterface {
$settings = $this->fieldDisplayInfo->getDisplaySettings($element);
if ($settings['wrapper'] !== 'default') {
try {
return $this->createInstance($settings['wrapper'], $settings['config']);
}
catch (PluginNotFoundException $e) {
// Not a valid wrapper plugin ID, skip and use the default theme_field.
}
}
return NULL;
}
}
