You are here

class ProviderPluginManager in Geocoder 8.3

Same name and namespace in other branches
  1. 8.2 src/ProviderPluginManager.php \Drupal\geocoder\ProviderPluginManager

Provides a plugin manager for geocoder providers.

Hierarchy

Expanded class hierarchy of ProviderPluginManager

8 files declare their use of ProviderPluginManager
AddressGeocodeFormatter.php in modules/geocoder_address/src/Plugin/Field/FieldFormatter/AddressGeocodeFormatter.php
DefaultField.php in modules/geocoder_field/src/Plugin/Geocoder/Field/DefaultField.php
FileGeocodeFormatter.php in modules/geocoder_field/src/Plugin/Field/FieldFormatter/FileGeocodeFormatter.php
GeocodeFormatterBase.php in modules/geocoder_field/src/Plugin/Field/GeocodeFormatterBase.php
GeocodeOrigin.php in src/Plugin/GeofieldProximitySource/GeocodeOrigin.php

... See full list

1 string reference to 'ProviderPluginManager'
geocoder.services.yml in ./geocoder.services.yml
geocoder.services.yml
1 service uses ProviderPluginManager
plugin.manager.geocoder.provider in ./geocoder.services.yml
Drupal\geocoder\ProviderPluginManager

File

src/ProviderPluginManager.php, line 21

Namespace

Drupal\geocoder
View source
class ProviderPluginManager extends GeocoderPluginManagerBase {
  use StringTranslationTrait;

  /**
   * The Renderer service property.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $renderer;

  /**
   * The Link generator Service.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $link;

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

  /**
   * The Drupal messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new geocoder provider plugin manager.
   *
   * @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
   *   The cache backend to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The Link Generator service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, TranslationInterface $string_translation, RendererInterface $renderer, LinkGeneratorInterface $link_generator, EntityTypeManagerInterface $entity_type_manager, MessengerInterface $messenger) {
    parent::__construct('Plugin/Geocoder/Provider', $namespaces, $module_handler, ProviderInterface::class, GeocoderProvider::class);
    $this
      ->alterInfo('geocoder_provider_info');
    $this
      ->setCacheBackend($cache_backend, 'geocoder_provider_plugins');
    $this->stringTranslation = $string_translation;
    $this->renderer = $renderer;
    $this->link = $link_generator;
    $this->entityTypeManager = $entity_type_manager;
    $this->messenger = $messenger;
  }

  /**
   * Returns the defined plugins.
   *
   * Note that this method has been changed in Geocoder 3.x. It currently
   * returns the list of plugin definitions which is identical to the list
   * returned by ::getDefinitions().
   *
   * In Geocoder 2.x this was returning a mix of plugin definitions and
   * configured providers but this architecture has been replaced by the new
   * GeocoderProvider config entity.
   *
   * It is recommended to no longer use this method but instead use one of these
   * two alternatives:
   *
   * In order to get a list of all available plugin definitions:
   * @code
   * $definitions = \Drupal\geocoder\ProviderPluginManager::getDefinitions();
   * @endcode
   *
   * In order to get a list of all geocoding providers that are configured by
   * the site builder:
   * @code
   * $providers = \Drupal\geocoder\Entity\GeocoderProvider::loadMultiple();
   * @endcode
   *
   * @return array
   *   A list of plugins.
   */
  public function getPlugins() : array {
    return $this
      ->getDefinitions();
  }

  /**
   * Generates the Draggable Table of Selectable Geocoder Plugins.
   *
   * @param array $enabled_provider_ids
   *   The IDs of the enabled Geocoder providers.
   *
   * @return array
   *   The plugins table list.
   */
  public function providersPluginsTableList(array $enabled_provider_ids) : array {
    $providers_link = $this->link
      ->generate(t('Geocoder providers configuration page'), Url::fromRoute('entity.geocoder_provider.collection', [], [
      'attributes' => [
        'target' => '_blank',
      ],
    ]));
    $options_field_description = [
      '#type' => 'html_tag',
      '#tag' => 'div',
      '#value' => $this
        ->t('Object literals in YAML format. Edit options in the @providers_link.', [
        '@providers_link' => $providers_link,
      ]),
      '#attributes' => [
        'class' => [
          'options-field-description',
        ],
      ],
    ];
    $caption = [
      'title' => [
        '#type' => 'html_tag',
        '#tag' => 'label',
        '#value' => $this
          ->t('Geocoder providers'),
      ],
      'caption' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => $this
          ->t('Select and reorder the Geocoder providers to use. The first one returning a valid value will be used.<br>If the provider of your choice does not appear here, you have to create it first in the @providers_link.', [
          '@providers_link' => $providers_link,
        ]),
      ],
    ];
    $element['plugins'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Name'),
        $this
          ->t('Weight'),
        $this
          ->t('Options<br>@options_field_description', [
          '@options_field_description' => $this->renderer
            ->renderRoot($options_field_description),
        ]),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'plugins-order-weight',
        ],
      ],
      '#caption' => $this->renderer
        ->renderRoot($caption),
      // We need this class for #states to hide the entire table.
      '#attributes' => [
        'class' => [
          'js-form-item',
          'geocode-plugins-list',
        ],
      ],
    ];

    // Reorder the plugins promoting the default ones in the proper order. By
    // initializing the enabled providers first they will appear at the top of
    // the list.
    $providers = [];
    foreach ($enabled_provider_ids as $enabled_provider_id) {
      $providers[$enabled_provider_id] = NULL;
    }
    foreach ($this->entityTypeManager
      ->getStorage('geocoder_provider')
      ->loadMultiple() as $provider_entity) {

      // Non-default values are appended at the end.
      $providers[$provider_entity
        ->id()]['entity'] = $provider_entity;
    }

    // Check if there are orphaned providers being configured. This might happen
    // if a provider is deleted if it is still in use.
    $orphaned_provider_ids = array_keys($providers, NULL, TRUE);
    if (!empty($orphaned_provider_ids)) {

      // Remove the orphaned providers.
      $providers = array_filter($providers);

      // Show a warning to the user.
      $warning = new PluralTranslatableMarkup(count($orphaned_provider_ids), 'The @providers Geocoder provider was not found and has been removed.', 'The following Geocoder providers were not found and have been removed: @providers', [
        '@providers' => implode(', ', $orphaned_provider_ids),
      ]);
      $this->messenger
        ->addWarning($warning);
    }
    if (empty($providers)) {
      $message = $this
        ->t('No Geocoding providers have been configured yet. Please create one in the @providers_link.', [
        '@providers_link' => $providers_link,
      ]);
      return [
        '#theme' => 'status_messages',
        '#message_list' => [
          'warning' => [
            $message,
          ],
        ],
        '#status_headings' => [
          'warning' => $this
            ->t('Warning message'),
        ],
      ];
    }
    $providers = array_map(function ($provider, $weight) use ($enabled_provider_ids) : array {

      /** @var \Drupal\geocoder\Entity\GeocoderProvider $provider_entity */
      $provider_entity = $provider['entity'];
      $checked = \in_array($provider_entity
        ->id(), $enabled_provider_ids, TRUE);
      return array_merge($provider, [
        'checked' => $checked,
        'weight' => $checked ? $weight : 0,
        'arguments' => $provider_entity
          ->isConfigurable() ? Yaml::encode($provider_entity
          ->get('configuration')) : (string) $this
          ->t("This plugin doesn't accept arguments."),
      ]);
    }, $providers, range(0, count($providers) - 1));
    uasort($providers, function ($providerA, $providerB) : int {
      $order = $providerB['checked'] <=> $providerA['checked'];
      if (0 === $order) {
        $order = $providerA['weight'] - $providerB['weight'];
        if (0 === $order) {
          $order = strcmp($providerA['entity']
            ->label(), $providerB['entity']
            ->label());
        }
      }
      return $order;
    });
    foreach ($providers as $provider) {

      /** @var \Drupal\geocoder\Entity\GeocoderProvider $provider_entity */
      $provider_entity = $provider['entity'];
      $element['plugins'][$provider_entity
        ->id()] = [
        'checked' => [
          '#type' => 'checkbox',
          '#title' => $provider_entity
            ->label(),
          '#default_value' => $provider['checked'],
        ],
        'weight' => [
          '#type' => 'weight',
          '#title' => $this
            ->t('Weight for @title', [
            '@title' => $provider_entity
              ->label(),
          ]),
          '#title_display' => 'invisible',
          '#default_value' => $provider['weight'],
          '#delta' => 20,
          '#attributes' => [
            'class' => [
              'plugins-order-weight',
            ],
          ],
        ],
        'arguments' => [
          '#type' => 'html_tag',
          '#tag' => 'pre',
          '#value' => $provider['arguments'],
        ],
        '#attributes' => [
          'class' => [
            'draggable',
          ],
        ],
      ];
    }
    return $element['plugins'];
  }

}

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::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides CachedDiscoveryInterface::clearCachedDefinitions 5
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
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
GeocoderPluginManagerBase::$geocodeSourceFieldsTypes protected property List of fields types available as source for Geocode operations.
GeocoderPluginManagerBase::$reverseGeocodeSourceFieldsTypes protected property List of fields types available as source for Reverse Geocode operations.
GeocoderPluginManagerBase::getGeocodeSourceFieldsTypes public function Gets a list of fields types available for Geocode operations.
GeocoderPluginManagerBase::getPluginsAsOptions public function Gets a list of available plugins to be used in forms.
GeocoderPluginManagerBase::getReverseGeocodeSourceFieldsTypes public function Gets a list of fields types available for Reverse Geocode operations.
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
ProviderPluginManager::$entityTypeManager protected property The entity type manager.
ProviderPluginManager::$link protected property The Link generator Service.
ProviderPluginManager::$messenger protected property The Drupal messenger service.
ProviderPluginManager::$renderer protected property The Renderer service property.
ProviderPluginManager::getPlugins public function Returns the defined plugins. Overrides GeocoderPluginManagerBase::getPlugins
ProviderPluginManager::providersPluginsTableList public function Generates the Draggable Table of Selectable Geocoder Plugins.
ProviderPluginManager::__construct public function Constructs a new geocoder provider plugin manager. Overrides DefaultPluginManager::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
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.