layout_builder_tomsaw-1.0.x-dev/src/GenericStylePluginManager.php

src/GenericStylePluginManager.php
<?php

declare(strict_types=1);

namespace Drupal\layout_builder_tomsaw;

use Drupal\ui_styles\StylePluginManager;
use Symfony\Component\Yaml\Yaml;

class GenericStylePluginManager extends StylePluginManager
{
  private array $reusable_options;

  private function getReusableOptions($key): array|null
  {
    // Lazy load
    if (!isset($this->reusable_options)) {
      $filename = 'layout_builder_tomsaw.ui_styles.generic.yml';
      $file_path = $this->moduleHandler->getModule('layout_builder_tomsaw')->getPath() . '/' . $filename;

      if (file_exists($file_path))
        $this->reusable_options = Yaml::parseFile($file_path);
      else
        throw new \Exception($filename . ' not found.');
    };

    if (isset($this->reusable_options[$key]))
      return $this->reusable_options[$key];
    else
      throw new \Exception("Generic option '$key' not found.");
  }
  private function getGenericOptions(string|array $selection): array
  {
    if(is_string($selection))
      return $this->getReusableOptions($selection);

    $options = [];
    foreach ($selection as $key) {
      $options += $this->getReusableOptions($key);
    }
    return $options;
  }

  public static function keyToPrefix(string $key): string
  {
    return join('', array_map(fn($v) => $v[0], explode('_', $key)));
  }

  public function processDefinition(&$definition, $plugin_id): void
  {
    // Generate repetive options
    // @todo use a Drupal\Core\Plugin\Discovery\DiscoveryDecorator instead?
    // @see https://www.drupal.org/docs/drupal-apis/plugin-api/discovery-decorators
    if (isset($definition['options']['generic'])) {
      $prefix = self::keyToPrefix($definition['id']);
      $generic_options = $this->getGenericOptions($definition['options']['generic']);
      foreach ($generic_options as $key => $value)
        $definition['options']["{$prefix}-{$key}"] = $value;

      unset($definition['options']['generic']);
    }

    parent::processDefinition($definition, $plugin_id);
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc