You are here

class DiffBuilderManager in Diff 8

Plugin type manager for field diff builders.

Plugin directory Plugin/diff/Field.

Hierarchy

Expanded class hierarchy of DiffBuilderManager

See also

\Drupal\diff\Annotation\FieldDiffBuilder

\Drupal\diff\FieldDiffBuilderInterface

Plugin API

1 file declares its use of DiffBuilderManager
FieldsSettingsForm.php in src/Form/FieldsSettingsForm.php
1 string reference to 'DiffBuilderManager'
diff.services.yml in ./diff.services.yml
diff.services.yml
1 service uses DiffBuilderManager
plugin.manager.diff.builder in ./diff.services.yml
Drupal\diff\DiffBuilderManager

File

src/DiffBuilderManager.php, line 26

Namespace

Drupal\diff
View source
class DiffBuilderManager extends DefaultPluginManager {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Wrapper object for simple configuration from diff.settings.yml.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * Wrapper object for simple configuration from diff.plugins.yml.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $pluginsConfig;

  /**
   * Static cache of field definitions per bundle and entity type.
   *
   * @var array
   */
  protected $pluginDefinitions;

  /**
   * Constructs a DiffBuilderManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory) {
    parent::__construct('Plugin/diff/Field', $namespaces, $module_handler, '\\Drupal\\diff\\FieldDiffBuilderInterface', 'Drupal\\diff\\Annotation\\FieldDiffBuilder');
    $this
      ->setCacheBackend($cache_backend, 'field_diff_builder_plugins');
    $this
      ->alterInfo('field_diff_builder_info');
    $this->entityTypeManager = $entity_type_manager;
    $this->config = $config_factory
      ->get('diff.settings');
    $this->pluginsConfig = $config_factory
      ->get('diff.plugins');
  }

  /**
   * Define whether a field should be displayed or not as a diff change.
   *
   * To define if a field should be displayed in the diff comparison, check if
   * it is revisionable and is not the bundle or revision field of the entity.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $field_storage_definition
   *   The field storage definition.
   *
   * @return bool
   *   TRUE if the field will be displayed.
   */
  public function showDiff(FieldStorageDefinitionInterface $field_storage_definition) {
    $show_diff = FALSE;

    // Check if the field is revisionable.
    if ($field_storage_definition
      ->isRevisionable()) {
      $show_diff = TRUE;

      // Do not display the field, if it is the bundle or revision field of the
      // entity.
      $entity_type = $this->entityTypeManager
        ->getDefinition($field_storage_definition
        ->getTargetEntityTypeId());

      // @todo Don't hard code fields after: https://www.drupal.org/node/2248983
      if (in_array($field_storage_definition
        ->getName(), [
        'revision_log',
        'revision_uid',
        $entity_type
          ->getKey('bundle'),
        $entity_type
          ->getKey('revision'),
      ])) {
        $show_diff = FALSE;
      }
    }
    return $show_diff;
  }

  /**
   * Creates a plugin instance for a field definition.
   *
   * Creates the instance based on the selected plugin for the field.
   *
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   *
   * @return \Drupal\diff\FieldDiffBuilderInterface|null
   *   The plugin instance, NULL if none.
   */
  public function createInstanceForFieldDefinition(FieldDefinitionInterface $field_definition) {
    $selected_plugin = $this
      ->getSelectedPluginForFieldStorageDefinition($field_definition
      ->getFieldStorageDefinition());
    if ($selected_plugin['type'] != 'hidden') {
      return $this
        ->createInstance($selected_plugin['type'], $selected_plugin['settings']);
    }
    return NULL;
  }

  /**
   * Selects a default plugin for a field storage definition.
   *
   * Checks if a plugin has been already selected for the field, otherwise
   * chooses one between the plugins that can be applied to the field.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition
   *   The field storage definition.
   *
   * @return array
   *   An array with the key type (which contains the plugin ID) and settings.
   *   The special type hidden indicates that the field should not be shown.
   */
  public function getSelectedPluginForFieldStorageDefinition(FieldStorageDefinitionInterface $field_definition) {
    $plugin_options = $this
      ->getApplicablePluginOptions($field_definition);
    $field_key = $field_definition
      ->getTargetEntityTypeId() . '.' . $field_definition
      ->getName();

    // Start with the stored configuration, this returns NULL if there is none.
    $selected_plugin = $this->pluginsConfig
      ->get('fields.' . $field_key);

    // If there is configuration and it is a valid type or exlplicitly set to
    // hidden, then use that, otherwise try to find a suitable default plugin.
    if ($selected_plugin && (in_array($selected_plugin['type'], array_keys($plugin_options)) || $selected_plugin['type'] == 'hidden')) {
      return $selected_plugin + [
        'settings' => [],
      ];
    }
    elseif (!empty($plugin_options) && $this
      ->isFieldStorageDefinitionDisplayed($field_definition)) {
      return [
        'type' => key($plugin_options),
        'settings' => [],
      ];
    }
    else {
      return [
        'type' => 'hidden',
        'settings' => [],
      ];
    }
  }

  /**
   * Determines if the field is displayed.
   *
   * Determines if a field should be displayed when comparing revisions based on
   * the entity view display if there is no plugin selected for the field.
   *
   * @param FieldStorageDefinitionInterface $field_storage_definition
   *   The field name.
   *
   * @return bool
   *   Whether the field is displayed.
   */
  public function isFieldStorageDefinitionDisplayed(FieldStorageDefinitionInterface $field_storage_definition) {
    if ($field_storage_definition instanceof BaseFieldDefinition && $field_storage_definition
      ->isDisplayConfigurable('view') || $field_storage_definition instanceof FieldStorageConfig) {
      $field_key = 'content.' . $field_storage_definition
        ->getName() . '.type';
      $storage = $this->entityTypeManager
        ->getStorage('entity_view_display');
      $query = $storage
        ->getQuery()
        ->condition('targetEntityType', $field_storage_definition
        ->getTargetEntityTypeId());
      if ($field_storage_definition instanceof FieldStorageConfig) {
        $bundles = $field_storage_definition
          ->getBundles();
        $query
          ->condition('bundle', (array) $bundles, 'IN');
      }
      $result = $query
        ->exists($field_key)
        ->range(0, 1)
        ->execute();
      return !empty($result) ? TRUE : FALSE;
    }
    else {
      $view_options = (bool) $field_storage_definition
        ->getDisplayOptions('view');
      return $view_options;
    }
  }

  /**
   * Gets the applicable plugin options for a given field.
   *
   * Loop over the plugins that can be applied to the field and builds an array
   * of possible plugins based on each plugin weight.
   *
   * @param FieldStorageDefinitionInterface $field_definition
   *   The field storage definition.
   *
   * @return array
   *   The plugin option for the given field based on plugin weight.
   */
  public function getApplicablePluginOptions(FieldStorageDefinitionInterface $field_definition) {
    $plugins = $this
      ->getPluginDefinitions();

    // Build a list of all diff plugins supporting the field type of the field.
    $plugin_options = [];
    if (isset($plugins[$field_definition
      ->getType()])) {

      // Sort the plugins based on their weight.
      uasort($plugins[$field_definition
        ->getType()], 'Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
      foreach ($plugins[$field_definition
        ->getType()] as $id => $weight) {
        $definition = $this
          ->getDefinition($id, FALSE);

        // Check if the plugin is applicable.
        if (isset($definition['class']) && in_array($field_definition
          ->getType(), $definition['field_types'])) {

          /** @var FieldDiffBuilderInterface $class */
          $class = $definition['class'];
          if ($class::isApplicable($field_definition)) {
            $plugin_options[$id] = $this
              ->getDefinitions()[$id]['label'];
          }
        }
      }
    }
    return $plugin_options;
  }

  /**
   * Initializes the local pluginDefinitions property.
   *
   * Loop over the plugin definitions and build an array keyed by the field type
   * that plugins can be applied to.
   *
   * @return array
   *   The initialized plugins array sort by field type.
   */
  public function getPluginDefinitions() {
    if (!isset($this->pluginDefinitions)) {

      // Get the definition of all the FieldDiffBuilder plugins.
      foreach ($this
        ->getDefinitions() as $plugin_definition) {
        if (isset($plugin_definition['field_types'])) {

          // Iterate through all the field types this plugin supports
          // and for every such field type add the id of the plugin.
          if (!isset($plugin_definition['weight'])) {
            $plugin_definition['weight'] = 0;
          }
          foreach ($plugin_definition['field_types'] as $id) {
            $this->pluginDefinitions[$id][$plugin_definition['id']]['weight'] = $plugin_definition['weight'];
          }
        }
      }
    }
    return $this->pluginDefinitions;
  }

  /**
   * Clear the pluginDefinitions local property array.
   */
  public function clearCachedDefinitions() {
    unset($this->pluginDefinitions);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional namespaces the annotation discovery mechanism should scan for annotation definitions.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition() if additional processing of plugins is necessary or helpful for development purposes. 9
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object that implements \Traversable which contains the root paths keyed by the corresponding namespace to look for plugin implementations.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins, or FALSE if the plugins are in the top level of the namespace.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 1
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::findDefinitions protected function Finds plugin definitions. 7
DefaultPluginManager::fixContextAwareDefinitions private function Fix the definitions of context-aware plugins.
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 12
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::processDefinition public function Performs extra processing on plugin definitions. 13
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 3
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DefaultPluginManager::useCaches public function Disable the use of caches. Overrides CachedDiscoveryInterface::useCaches 1
DiffBuilderManager::$config protected property Wrapper object for simple configuration from diff.settings.yml.
DiffBuilderManager::$entityTypeManager protected property The entity type manager.
DiffBuilderManager::$pluginDefinitions protected property Static cache of field definitions per bundle and entity type.
DiffBuilderManager::$pluginsConfig protected property Wrapper object for simple configuration from diff.plugins.yml.
DiffBuilderManager::clearCachedDefinitions public function Clear the pluginDefinitions local property array. Overrides DefaultPluginManager::clearCachedDefinitions
DiffBuilderManager::createInstanceForFieldDefinition public function Creates a plugin instance for a field definition.
DiffBuilderManager::getApplicablePluginOptions public function Gets the applicable plugin options for a given field.
DiffBuilderManager::getPluginDefinitions public function Initializes the local pluginDefinitions property.
DiffBuilderManager::getSelectedPluginForFieldStorageDefinition public function Selects a default plugin for a field storage definition.
DiffBuilderManager::isFieldStorageDefinitionDisplayed public function Determines if the field is displayed.
DiffBuilderManager::showDiff public function Define whether a field should be displayed or not as a diff change.
DiffBuilderManager::__construct public function Constructs a DiffBuilderManager object. Overrides DefaultPluginManager::__construct
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryCachedTrait::getDefinition public function Overrides DiscoveryTrait::getDefinition 3
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::createInstance public function Creates a pre-configured instance of a plugin. Overrides FactoryInterface::createInstance 12
PluginManagerBase::getInstance public function Gets a preconfigured instance of a plugin. Overrides MapperInterface::getInstance 7
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag. 1
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.