You are here

class BootstrapLayoutsManager in Bootstrap Layouts 8.4

Same name and namespace in other branches
  1. 8.5 src/BootstrapLayoutsManager.php \Drupal\bootstrap_layouts\BootstrapLayoutsManager

Class BootstrapLayoutsManager

Hierarchy

Expanded class hierarchy of BootstrapLayoutsManager

2 files declare their use of BootstrapLayoutsManager
BootstrapLayoutsUpdateBase.php in src/Plugin/BootstrapLayouts/BootstrapLayoutsUpdateBase.php
BootstrapLayoutsUpdateInterface.php in src/Plugin/BootstrapLayouts/BootstrapLayoutsUpdateInterface.php
1 string reference to 'BootstrapLayoutsManager'
bootstrap_layouts.services.yml in ./bootstrap_layouts.services.yml
bootstrap_layouts.services.yml
1 service uses BootstrapLayoutsManager
plugin.manager.bootstrap_layouts in ./bootstrap_layouts.services.yml
\Drupal\bootstrap_layouts\BootstrapLayoutsManager

File

src/BootstrapLayoutsManager.php, line 19

Namespace

Drupal\bootstrap_layouts
View source
class BootstrapLayoutsManager extends BootstrapLayoutsPluginManager {

  /**
   * @var \Drupal\layout_plugin\Plugin\Layout\LayoutPluginManager
   */
  protected $layoutManager;

  /**
   * @var \Drupal\bootstrap_layouts\BootstrapLayoutsUpdateManager
   */
  protected $updateManager;

  /**
   * Constructs a new \Drupal\bootstrap_layouts\BootstrapLayoutsManager 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 to invoke the alter hook with.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme manager used to invoke the alter hook with.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager used to invoke the alter hook with.
   * @param \Drupal\layout_plugin\Plugin\Layout\LayoutPluginManager $layout_manager
   *   The Layout Manager.
   * @param \Drupal\bootstrap_layouts\BootstrapLayoutsUpdateManager $update_manager
   *   The Bootstrap Layouts update manager.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler, ThemeManagerInterface $theme_manager, LayoutPluginManager $layout_manager, BootstrapLayoutsUpdateManager $update_manager) {
    parent::__construct($namespaces, $cache_backend, $module_handler, $theme_handler, $theme_manager, 'Drupal\\bootstrap_layouts\\Plugin\\BootstrapLayouts\\BootstrapLayoutsHandlerInterface', 'Drupal\\bootstrap_layouts\\Annotation\\BootstrapLayoutsHandler');
    $this->layoutManager = $layout_manager;
    $this->updateManager = $update_manager;
    $this
      ->alterInfo('bootstrap_layouts_handler_info');
    $this
      ->setCacheBackend($cache_backend, 'bootstrap_layouts_handler_info');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('container.namespaces'), $container
      ->get('cache.discovery'), $container
      ->get('module_handler'), $container
      ->get('theme_handler'), $container
      ->get('theme.manager'), $container
      ->get('plugin.manager.layout_plugin'), $container
      ->get('plugin.manager.bootstrap_layouts.update'));
  }

  /**
   * {@inheritdoc}
   */
  protected function findDefinitions() {
    $definitions = parent::findDefinitions();

    // The handler plugin identifiers represent the module or theme that
    // implements said layouts. Remove any handler plugins that not installed.
    foreach (array_keys($definitions) as $provider) {
      if (!$this
        ->providerExists($provider)) {
        unset($definitions[$provider]);
      }
      else {

        // Attempt to retrieve the theme human readable label first.
        try {
          $label = $this->themeHandler
            ->getName($provider);
        } catch (\Exception $e) {
          $label = $this->moduleHandler
            ->getName($provider);
        }
        $definitions[$provider]['label'] = $label;
      }
    }
    return $definitions;
  }

  /**
   * Retrieves classes that can be used in Bootstrap layouts as select options.
   *
   * @return array
   *   An associative array of grouped classes to be used in select options.
   */
  public function getClassOptions() {
    static $classes;
    if (!isset($classes)) {
      $utility = [];
      $col = [];
      $hidden = [];
      $visible = [];
      $bg = [];
      $text_color = [];
      $text_alignment = [
        'text-left' => $this
          ->t('Left'),
        'text-right' => $this
          ->t('Right'),
        'text-center' => $this
          ->t('Center'),
        'text-justify' => $this
          ->t('Justify'),
        'text-nowrap' => $this
          ->t('No Wrap'),
      ];
      $text_transformation = [
        'text-lowercase' => $this
          ->t('Lowercase'),
        'text-uppercase' => $this
          ->t('Uppercase'),
        'text-capitalize' => $this
          ->t('Capitalize'),
      ];

      // Utility.
      $utility['clearfix'] = $this
        ->t('Clear Fix');
      $utility['row'] = $this
        ->t('Row');
      $sizes = [
        'xs' => $this
          ->t('Extra Small'),
        'sm' => $this
          ->t('Small'),
        'md' => $this
          ->t('Medium'),
        'lg' => $this
          ->t('Large'),
      ];
      foreach ($sizes as $size => $size_label) {
        $hidden["hidden-{$size}"] = $size_label;
        $visible["visible-{$size}"] = $size_label;
        foreach (range(1, 12) as $column) {
          $col["col-{$size}-{$column}"] = $this
            ->t('@size: @column', [
            '@size' => $size_label,
            '@column' => $column,
          ]);
        }
      }

      // Background/text color classes.
      foreach ([
        'primary',
        'danger',
        'info',
        'warning',
        'success',
      ] as $type) {
        $bg["bg-{$type}"] = $this
          ->t('@type', [
          '@type' => Unicode::ucfirst($type),
        ]);
        $text_color["text-{$type}"] = $this
          ->t('@type', [
          '@type' => Unicode::ucfirst($type),
        ]);
      }
      $text_color['text-muted'] = $this
        ->t('Muted');

      // Groups.
      $groups = [
        'utility' => $this
          ->t('Utility'),
        'columns' => $this
          ->t('Columns'),
        'hidden' => $this
          ->t('Hidden'),
        'visible' => $this
          ->t('Visible'),
        'background' => $this
          ->t('Background'),
        'text_alignment' => $this
          ->t('Text alignment'),
        'text_color' => $this
          ->t('Text color'),
        'text_transformation' => $this
          ->t('Text transformation'),
      ];

      // Classes, keyed by group.
      $classes = [
        'utility' => $utility,
        'columns' => $col,
        'hidden' => $hidden,
        'visible' => $visible,
        'background' => $bg,
        'text_alignment' => $text_alignment,
        'text_color' => $text_color,
        'text_transformation' => $text_transformation,
      ];

      // Invokes hook_bootstrap_layouts_class_options_alter().
      $this->moduleHandler
        ->alter('bootstrap_layouts_class_options', $classes, $groups);
      $this->themeManager
        ->alter('bootstrap_layouts_class_options', $classes, $groups);

      // Render the group labels and use them for optgroup values.
      $grouped = [];
      foreach ($classes as $group => $data) {
        $group = (string) (isset($groups[$group]) ? $groups[$group] : $group);
        $grouped[$group] = $data;
      }
      $classes = $grouped;
    }
    return $classes;
  }

  /**
   * Indicates if provided layout identifier is a Bootstrap Layouts layout.
   *
   * @param string $id
   *   The layout identifier to test.
   *
   * @return bool
   *   TRUE or FALSE
   */
  public function isBootstrapLayout($id) {
    static $layouts;
    if (!isset($layouts)) {
      $layouts = [];
      foreach (array_keys($this->layoutManager
        ->getDefinitions()) as $layout_id) {
        $plugin = $this->layoutManager
          ->createInstance($layout_id);
        if ($plugin instanceof BootstrapLayoutsBase) {
          $layouts[] = $layout_id;
        }
      }
    }
    return in_array($id, $layouts);
  }

  /**
   * Retrieves all available handler instances.
   *
   * @return \Drupal\bootstrap_layouts\Plugin\BootstrapLayouts\BootstrapLayoutsHandlerInterface[]
   */
  public function getHandlers() {
    $instances = [];
    foreach (array_keys($this
      ->getDefinitions()) as $plugin_id) {
      $instances[$plugin_id] = $this
        ->createInstance($plugin_id);
    }
    return $instances;
  }

  /**
   * Runs update(s) for a specific schema version.
   *
   * @param int $schema
   *   The schema version to update.
   * @param bool $display_messages
   *   Flag determining whether a message will be displayed indicating whether
   *   the layout was processed successfully or not.
   */
  public function update($schema, $display_messages = TRUE) {
    $handlers = $this
      ->getHandlers();
    $data = [];
    foreach ($this->updateManager
      ->getUpdates($schema) as $update) {

      // See if there's an adjoining YML file with the update plugin.
      $r = new \ReflectionClass($update);
      $data_paths = [
        dirname($r
          ->getFileName()),
        $update
          ->getPath(),
      ];

      // Merge in any update data.
      foreach ($data_paths as $path) {
        $file = "{$path}/bootstrap_layouts.update.{$schema}.yml";
        if (file_exists($file) && ($yaml = Yaml::decode(file_get_contents($file)))) {
          $data = NestedArray::mergeDeep($data, $yaml);
        }
      }

      // Perform the update.
      $update
        ->update($this, $data, $display_messages);

      // Process any existing layouts after the update.
      foreach ($handlers as $handler_id => $handler) {
        foreach ($handler
          ->loadInstances() as $storage_id => $layout) {
          $update
            ->processExistingLayout($layout, $data, $display_messages);

          // Determine if the layout has changed and then save it.
          if ($layout
            ->hasChanged()) {
            try {
              $handler
                ->saveInstance($storage_id, $layout);
              if ($display_messages) {
                \drupal_set_message($this
                  ->t('Successfully updated the existing Bootstrap layout found in "@id".', [
                  '@id' => $storage_id,
                ]));
              }
            } catch (\Exception $e) {
              \drupal_set_message($this
                ->t('Unable to update the existing Bootstrap layout found in "@id":', [
                '@id' => $storage_id,
              ]), 'error');
              \drupal_set_message($e
                ->getMessage(), 'error');
            }
          }
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BootstrapLayoutsManager::$layoutManager protected property
BootstrapLayoutsManager::$updateManager protected property
BootstrapLayoutsManager::create public static function Instantiates a new instance of this class. Overrides BootstrapLayoutsPluginManager::create
BootstrapLayoutsManager::findDefinitions protected function Finds plugin definitions. Overrides DefaultPluginManager::findDefinitions
BootstrapLayoutsManager::getClassOptions public function Retrieves classes that can be used in Bootstrap layouts as select options.
BootstrapLayoutsManager::getHandlers public function Retrieves all available handler instances.
BootstrapLayoutsManager::isBootstrapLayout public function Indicates if provided layout identifier is a Bootstrap Layouts layout.
BootstrapLayoutsManager::update public function Runs update(s) for a specific schema version.
BootstrapLayoutsManager::__construct public function Constructs a new \Drupal\bootstrap_layouts\BootstrapLayoutsManager object. Overrides BootstrapLayoutsPluginManager::__construct
BootstrapLayoutsPluginManager::$themeHandler protected property
BootstrapLayoutsPluginManager::$themeManager protected property
BootstrapLayoutsPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. Overrides DefaultPluginManager::alterDefinitions
BootstrapLayoutsPluginManager::providerExists protected function Determines if the provider of a definition exists. Overrides DefaultPluginManager::providerExists
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::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::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::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
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.
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.