You are here

class FreelinkingManager in Freelinking 8.3

Same name and namespace in other branches
  1. 4.0.x src/FreelinkingManager.php \Drupal\freelinking\FreelinkingManager

Freelinking plugin manager.

Hierarchy

Expanded class hierarchy of FreelinkingManager

1 file declares its use of FreelinkingManager
FreelinkingManagerTest.php in tests/src/Unit/FreelinkingManagerTest.php
1 string reference to 'FreelinkingManager'
freelinking.services.yml in ./freelinking.services.yml
freelinking.services.yml
1 service uses FreelinkingManager
freelinking.manager in ./freelinking.services.yml
Drupal\freelinking\FreelinkingManager

File

src/FreelinkingManager.php, line 17

Namespace

Drupal\freelinking
View source
class FreelinkingManager extends DefaultPluginManager implements FreelinkingManagerInterface, TrustedCallbackInterface {
  use StringTranslationTrait;

  /**
   * Language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Builtin pseudo-plugin ids.
   *
   * @var array
   */
  protected $builtin = [
    'showtext',
    'nowiki',
    'redacted',
  ];

  /**
   * {@inheritdoc}
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager) {
    parent::__construct('Plugin/freelinking', $namespaces, $module_handler, '\\Drupal\\freelinking\\Plugin\\FreelinkingPluginInterface', '\\Drupal\\freelinking\\Annotation\\Freelinking');
    $this
      ->alterInfo('freelinking_plugin_info');
    $this
      ->setCacheBackend($cache_backend, 'freelinking');
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginFromIndicator($indicator, array $allowed_plugins = [], array $options = []) {
    $current_plugin = FALSE;
    $default_configuration = [
      'settings' => [],
    ];
    try {
      if ('showtext' === $indicator || 'nowiki' === $indicator || 'redact' === $indicator) {
        return $this
          ->createInstance('builtin', []);
      }
      foreach ($allowed_plugins as $plugin_name => $plugin_info) {

        /** @var \Drupal\freelinking\Plugin\FreelinkingPluginInterface $plugin */
        $default_configuration['settings'] = isset($plugin_info['settings']) ? $plugin_info['settings'] : [];
        $plugin = $this
          ->createInstance($plugin_name, $default_configuration);
        if (preg_match($plugin
          ->getIndicator(), $indicator)) {
          $current_plugin = $plugin;
        }
      }

      // Set the current plugin to nodetitle if it is the default.
      if (!$options['global_options']['ignore_upi'] && in_array('nodetitle', $allowed_plugins) && 'nodetitle' === $options['default'] && !$current_plugin) {
        $default_configuration['settings'] = $allowed_plugins['nodetitle']['settings'];
        $current_plugin = $this
          ->createInstance('nodetitle', $default_configuration);
      }
      return $current_plugin;
    } catch (PluginNotFoundException $e) {
      return $current_plugin;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildLink(FreelinkingPluginInterface $plugin, array $target) {
    $link = $plugin
      ->buildLink($target);

    // Allow modules a chance to alter the freelink link array for complex
    // plugins that return an array.
    if (is_array($link)) {
      $data = [
        'target' => $target,
        'plugin_name' => $plugin
          ->getPluginId(),
        'plugin' => $plugin,
      ];
      $this->moduleHandler
        ->alter('freelinking_freelink', $link, $data);
    }
    return $link;
  }

  /**
   * {@inheritdoc}
   */
  public function parseTarget($target, $langcode) {
    $args = [];
    $args['target'] = $target;
    $args['other'] = [];
    $items = explode('|', $target);

    /*
     * Each argument in the target string has three possibilities:
     *
     * - Unnamed: the first three argument sare dest, text and tooltip.
     * - INI: arguments can be delimited by key=value pairs.
     * - Other: Anything else is appended to an indexed array.
     */
    $index = 0;
    foreach ($items as $key => $item) {
      if ($index < 3) {
        switch ($index) {
          case 0:
            $args['dest'] = $item;
            break;
          case 1:
            $args['text'] = $item;
            break;
          case 2:
            $args['tooltip'] = $item;
            break;
        }
        $index++;
      }
      elseif (strpos($item, '=')) {
        [
          $name,
          $value,
        ] = explode('=', $item);
        $args[$name] = $value;
      }
      else {
        $args['other'][] = $item;
      }
    }

    // Convert URL-encoded text into something readable for link text & tooltip.
    $args['text'] = isset($args['text']) ? urldecode($args['text']) : NULL;
    $args['tooltip'] = isset($args['tooltip']) ? urldecode($args['tooltip']) : NULL;
    $args['language'] = $this->languageManager
      ->getLanguage($langcode);
    return $args;
  }

  /**
   * {@inheritdoc}
   */
  public function createErrorElement($indicator) {
    $message = $this
      ->t('Missing plugin indicator');
    if ('NONE' !== $indicator) {
      $message = $this
        ->t('Unknown plugin indicator');
    }
    return [
      '#theme' => [
        'freelink_error',
        'freelink_error__' . $indicator,
      ],
      '#message' => $message,
      '#plugin' => $indicator,
      '#attributes' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function createFreelinkElement($plugin_id, $target, $indicator, $langcode, $plugin_settings_string, $failover_settings_string) {
    $plugin_settings = unserialize($plugin_settings_string);
    $configuration = [
      'settings' => isset($plugin_settings['settings']) ? $plugin_settings['settings'] : [],
    ];

    /** @var \Drupal\freelinking\Plugin\FreelinkingPluginInterface $plugin */
    $plugin = $this
      ->createInstance($plugin_id, $configuration);
    $config = $plugin
      ->getConfiguration();
    $target_array = $this
      ->parseTarget($target, $langcode);
    $target_array['indicator'] = $indicator;
    $link = $this
      ->buildLink($plugin, $target_array);
    if (is_array($link) && isset($link['error']) && isset($config['settings']['failover'])) {

      /** @var \Drupal\freelinking\Plugin\FreelinkingPluginInterface $failover_plugin */
      $failover_settings = unserialize($failover_settings_string);
      $failover_plugin_id = $config['settings']['failover'];
      $default_configuration = [
        'settings' => isset($failover_settings['settings']) ? $failover_settings['settings'] : [],
      ];
      if (in_array($failover_plugin_id, $this->builtin)) {

        // Changes plugin indicator to the failover plugin ID for the builtin
        // plugin.
        $failover_plugin_id = 'builtin';
        $target_array['indicator'] = $config['settings']['failover'];
      }
      $failover_plugin = $this
        ->createInstance($failover_plugin_id, $default_configuration);
      $target_array['indicator'] = $config['settings']['failover'];
      $link = $this
        ->buildLink($failover_plugin, $target_array);
    }

    // Drupal currently does not allow returning a render element that only does
    // #pre_render as part of a lazy builder context. This wraps the render
    // array within a small theme function.
    return [
      '#theme' => [
        'freelink',
        'freelink__' . $plugin_id,
      ],
      '#link' => $link,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return [
      'createFreelinkElement',
      'createErrorElement',
    ];
  }

}

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
FreelinkingManager::$builtin protected property Builtin pseudo-plugin ids.
FreelinkingManager::$languageManager protected property Language manager.
FreelinkingManager::buildLink public function Build link structure for a plugin with target parameters. Overrides FreelinkingManagerInterface::buildLink
FreelinkingManager::createErrorElement public function Create the error element when plugin not found. Overrides FreelinkingManagerInterface::createErrorElement
FreelinkingManager::createFreelinkElement public function Create the render array for the respective Freelinking plugin. Overrides FreelinkingManagerInterface::createFreelinkElement
FreelinkingManager::getPluginFromIndicator public function Get the plugin to use based on the indicator and a list of allowed plugins. Overrides FreelinkingManagerInterface::getPluginFromIndicator
FreelinkingManager::parseTarget public function Parse link arguments from the target string. Overrides FreelinkingManagerInterface::parseTarget
FreelinkingManager::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
FreelinkingManager::__construct public function Creates the discovery object. Overrides DefaultPluginManager::__construct
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
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.
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.