devel_wizard-2.x-dev/src/Plugin/DevelWizard/Spell/ParagraphBehaviorSpell.php

src/Plugin/DevelWizard/Spell/ParagraphBehaviorSpell.php
<?php

declare(strict_types=1);

namespace Drupal\devel_wizard\Plugin\DevelWizard\Spell;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Template\TwigEnvironment;
use Drupal\devel_wizard\Attribute\DevelWizardSpell;
use Drupal\devel_wizard\Utils;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;

#[DevelWizardSpell(
  id: 'devel_wizard_paragraph_behavior',
  category: new TranslatableMarkup('Code'),
  label: new TranslatableMarkup('Paragraph Behavior'),
  description: new TranslatableMarkup('Generates a new Paragraph Behavior plugin.'),
  tags: [
    'code' => new TranslatableMarkup('Code'),
    'paragraph' => new TranslatableMarkup('Paragraph'),
    'plugin' => new TranslatableMarkup('Plugin'),
  ],
)]
class ParagraphBehaviorSpell extends SpellBase implements
  PluginFormInterface,
  ConfigurableInterface,
  ContainerFactoryPluginInterface {

  public static function create(
    ContainerInterface $container,
    array $configuration,
    $plugin_id,
    $plugin_definition,
  ) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('messenger'),
      $container->get('logger.channel.devel_wizard_spell'),
      $container->get('string_translation'),
      $container->get('devel_wizard.utils'),
      $container->get('config.factory'),
      $container->get('extension.list.module'),
      $container->get('twig'),
      new Filesystem(),
    );
  }

  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    MessengerInterface $messenger,
    LoggerInterface $logger,
    TranslationInterface $stringTranslation,
    Utils $utils,
    ConfigFactoryInterface $configFactory,
    protected ModuleExtensionList $moduleList,
    protected TwigEnvironment $twig,
    protected Filesystem $fs,
  ) {
    parent::__construct(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $messenger,
      $logger,
      $stringTranslation,
      $utils,
      $configFactory,
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return [
      'extension' => [
        'machineName' => '',
      ],
      'plugin' => [
        'id' => '',
      ],
    ];
  }

  protected function populateCalculatedConfigurationValues(): static {
    parent::populateCalculatedConfigurationValues();

    if (empty($this->configuration['extension']['machineName'])) {
      throw new \InvalidArgumentException(sprintf(
        '%s can not be empty',
        'extension.machineName',
      ));
    }

    if (empty($this->configuration['plugin']['id'])) {
      throw new \InvalidArgumentException(sprintf(
        '%s can not be empty',
        'plugin.id',
      ));
    }

    $extension = $this->moduleList->get($this->configuration['extension']['machineName']);
    $this->configuration['baseDir'] = $extension->getPath();
    $this->configuration['extension'] += $this->utils->stringVariants(
      $this->configuration['extension']['machineName'],
      'machineName',
    );

    $this->configuration['plugin'] += $this->utils->stringVariants(
      $this->configuration['plugin']['id'],
      'id',
    );
    $this->configuration['plugin']['idShort'] = preg_replace(
      '/^' . preg_quote($this->configuration['extension']['machineName'], '/') . '_/',
      '',
      $this->configuration['plugin']['id'],
    );
    $this->configuration['plugin'] += $this->utils->stringVariants(
      $this->configuration['plugin']['idShort'],
      'idShort',
    );
    $this->configuration['plugin'] += [
      'label' => $this->configuration['plugin']['id'],
      'description' => "This is the description of the {$this->configuration['plugin']['id']}",
    ];

    $this->configuration['class'] = [
      'name' => $this->configuration['plugin']['idShortUpperCamel'],
      'namespace' => "Drupal\\{$this->configuration['extension']['machineName']}\\Plugin\\paragraphs\\Behavior",
    ];
    $this->configuration['class'] += [
      'fqn' => "{$this->configuration['class']['namespace']}\\{$this->configuration['class']['name']}",
      'filePath' => Path::join(
        $this->configuration['baseDir'],
        'src',
        'Plugin',
        'paragraphs',
        'Behavior',
        $this->configuration['class']['name'] . '.php',
      ),
    ];

    return $this;
  }

  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $conf = $this->getConfiguration();
    $form['#attributes']['class'][] = 'dws--paragraph-behavior';
    $form['#attached']['library'][] = 'devel_wizard/spell.paragraph_behavior';

    $form['extension'] = [
      '#type' => 'details',
      '#tree' => TRUE,
      '#title' => $this->t('Module'),
      '#open' => TRUE,

      'machineName' => [
        '#type' => 'textfield',
        '#title' => $this->t('Machine-name'),
        '#default_value' => $conf['extension']['machineName'],
        '#description' => $this->t('Machine-name of the module to put the new code files into.'),
        '#autocomplete_route_name' => 'devel_wizard.autocomplete.module',
      ],
    ];

    $form['plugin'] = [
      '#type' => 'details',
      '#tree' => TRUE,
      '#title' => $this->t('plugin'),
      '#open' => TRUE,

      'id' => [
        '#type' => 'textfield',
        '#required' => TRUE,
        '#title' => $this->t('Identifier of the layout'),
        '#default_value' => $conf['plugin']['id'],
        '#field_prefix' => '&lt;extension.machineName&gt;_',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    // @todo Implement validateConfigurationForm() method.
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
    $values = $form_state->getValue($form['#parents'], []);
    $values['plugin']['id'] = sprintf(
      '%s_%s',
      $values['extension']['machineName'],
      $values['plugin']['id'],
    );
    $this->setConfiguration($values);
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doIt(): static {
    $this->doItCode();

    drupal_flush_all_caches();

    $this->batchContext['finished'] = 1.0;

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItCode(): static {
    $schemeFilePath = Path::join(
      $this->configuration['baseDir'],
      'config',
      'scheme',
      "{$this->configuration['extension']['machineName']}.scheme.yml",
    );
    $this->utils->ymlFileReplace(
      $schemeFilePath,
      [
        "paragraphs.behavior.settings.{$this->configuration['plugin']['id']}" => [
          'type' => 'paragraphs.behavior.settings_base',
          'mapping' => [
            'allowed_options' => [
              'type' => 'sequence',
              'sequence' => [
                'type' => 'string',
              ],
            ],
          ],
        ],
      ],
    );

    foreach ($this->getTwigFiles() as $dstFilePath => $template) {
      $dstFileContent = $this->twig->render(
        $template,
        $this->configuration,
      );
      $this->fs->mkdir(Path::getDirectory($dstFilePath));
      $this->fs->dumpFile($dstFilePath, $dstFileContent);
      $this->messageFilesystemEntryCreate($dstFilePath);
    }

    return $this;
  }

  protected function getTwigFiles(): array {
    return [
      $this->configuration['class']['filePath'] => '@devel_wizard/spell/paragraph_behavior/class.php.twig',
    ];
  }

}

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

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