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

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

declare(strict_types=1);

namespace Drupal\devel_wizard\Plugin\DevelWizard\Spell;

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\ShellProcessFactoryInterface;
use Drupal\devel_wizard\Spell\SpellTraitPackageManager;
use Drupal\devel_wizard\Utils;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\String\UnicodeString;

#[DevelWizardSpell(
  id: 'devel_wizard_plugin_manager',
  category: new TranslatableMarkup('Code'),
  label: new TranslatableMarkup('Plugin manager'),
  description: new TranslatableMarkup('Generates a minimal code for a new Plugin API.'),
  tags: [
    'code' => new TranslatableMarkup('Code'),
    'plugin' => new TranslatableMarkup('Plugin'),
    'manager' => new TranslatableMarkup('Manager'),
  ],
)]
class PluginManagerSpell extends SpellBase implements
  PluginFormInterface,
  ContainerFactoryPluginInterface {

  use SpellTraitPackageManager;

  protected ModuleExtensionList $moduleList;

  protected TwigEnvironment $twig;

  protected Filesystem $fs;

  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('devel_wizard.shell_process_factory'),
      $container->get('extension.list.module'),
      $container->get('twig'),
      new Filesystem(),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    MessengerInterface $messenger,
    LoggerInterface $logger,
    TranslationInterface $stringTranslation,
    Utils $utils,
    ConfigFactoryInterface $configFactory,
    ShellProcessFactoryInterface $shellProcessFactory,
    ModuleExtensionList $moduleList,
    TwigEnvironment $twig,
    Filesystem $fs,
  ) {
    $this->shellProcessFactory = $shellProcessFactory;
    $this->moduleList = $moduleList;
    $this->twig = $twig;
    $this->fs = $fs;
    parent::__construct(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $messenger,
      $logger,
      $stringTranslation,
      $utils,
      $configFactory,
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'module' => '',
      'object' => '',
    ];
  }

  protected function populateCalculatedConfigurationValues(): static {
    parent::populateCalculatedConfigurationValues();
    $conf =& $this->configuration;

    if (empty($conf['module'])) {
      throw new \InvalidArgumentException('module is required');
    }

    if (empty($conf['object'])) {
      throw new \InvalidArgumentException('object is required');
    }

    $conf['moduleDir'] = $this->moduleList->getPath($conf['module']);
    $conf['moduleUpperCamel'] = (new UnicodeString("a_{$conf['module']}"))
      ->camel()
      ->trimPrefix('a')
      ->toString();

    $conf['objectUpperCamel'] = (new UnicodeString("a_{$conf['object']}"))
      ->camel()
      ->trimPrefix('a')
      ->toString();

    $conf['objectLowerCamel'] = (new UnicodeString($conf['object']))
      ->camel()
      ->toString();

    $conf['objectDir'] = Path::join(
      $conf['moduleDir'],
      'src',
      $conf['objectUpperCamel'],
    );

    $conf['objectNamespace'] = "Drupal\\{$conf['module']}\\{$conf['objectUpperCamel']}";

    $conf['label'] = $conf['objectUpperCamel'];

    $conf['definition'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}Definition",
    ];
    $conf['definition']['classFqn'] = "{$conf['definition']['namespace']}\\{$conf['definition']['class']}";
    $conf['definition']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['definition']['class']}.php",
    );

    $conf['annotation'] = [
      'namespace' => "Drupal\\{$conf['module']}\\Annotation",
      'class' => "{$conf['moduleUpperCamel']}{$conf['objectUpperCamel']}",
    ];
    $conf['annotation']['classFqn'] = "{$conf['annotation']['namespace']}\\{$conf['annotation']['class']}";
    $conf['annotation']['filePath'] = Path::join(
      $conf['moduleDir'],
      'src',
      'Annotation',
      "{$conf['annotation']['class']}.php",
    );

    $conf['definitionComparer'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}DefinitionComparer",
    ];
    $conf['definitionComparer']['classFqn'] = "{$conf['definitionComparer']['namespace']}\\{$conf['definitionComparer']['class']}";
    $conf['definitionComparer']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['definitionComparer']['class']}.php",
    );
    $conf['definitionComparer']['service'] = [
      'id' => "{$conf['module']}.{$conf['object']}.definition_comparer",
      'definition' => [
        'class' => $conf['definitionComparer']['classFqn'],
        'shared' => FALSE,
      ],
    ];

    $conf['pluginInterface'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}Interface",
    ];
    $conf['pluginInterface']['classFqn'] = "{$conf['pluginInterface']['namespace']}\\{$conf['pluginInterface']['class']}";
    $conf['pluginInterface']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['pluginInterface']['class']}.php",
    );

    $conf['managerInterface'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}ManagerInterface",
    ];
    $conf['managerInterface']['classFqn'] = "{$conf['managerInterface']['namespace']}\\{$conf['managerInterface']['class']}";
    $conf['managerInterface']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['managerInterface']['class']}.php",
    );

    $conf['manager'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}Manager",
    ];
    $conf['manager']['classFqn'] = "{$conf['manager']['namespace']}\\{$conf['manager']['class']}";
    $conf['manager']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['manager']['class']}.php",
    );
    $conf['manager']['service'] = [
      'id' => "plugin.manager.{$conf['module']}.{$conf['object']}",
      'definition' => [
        'class' => $conf['manager']['classFqn'],
        'arguments' => [
          '@container.namespaces',
          '@module_handler',
          '@cache.discovery',
          "@{$conf['definitionComparer']['service']['id']}",
        ],
      ],
    ];

    $conf['paramConverter'] = [
      'namespace' => $conf['objectNamespace'],
      'class' => "{$conf['objectUpperCamel']}ParamConverter",
    ];
    $conf['paramConverter']['classFqn'] = "{$conf['paramConverter']['namespace']}\\{$conf['paramConverter']['class']}";
    $conf['paramConverter']['filePath'] = Path::join(
      $conf['objectDir'],
      "{$conf['paramConverter']['class']}.php",
    );
    $conf['paramConverter']['service'] = [
      'id' => "{$conf['module']}.{$conf['object']}.param_converter",
      'definition' => [
        'class' => $conf['paramConverter']['classFqn'],
        'arguments' => [
          '@' . $conf['manager']['service']['id'],
        ],
        'tags' => [
          [
            'name' => 'paramconverter',
          ],
        ],
      ],
    ];

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $conf = $this->getConfiguration();

    $form['module'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this->t('Module'),
      '#default_value' => $conf['module'],
      '#autocomplete_route_name' => 'devel_wizard.autocomplete.module',
    ];

    $form['object'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this->t('Machine-name of the new Plugin API'),
      '#default_value' => $conf['object'],
    ];

    return $form;
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration = $form_state->getValue($form['#parents'], []);
    $this->setConfiguration($configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function getRequiredPackagesProd(): array {
    $packages = parent::getRequiredPackagesProd();
    $packages['sweetchuck/utils'] = '1.x-dev';

    return $packages;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doIt(): static {
    if (!isset($this->batchContext['sandbox']['current_step'])) {
      $this->batchContext['message'] = $this->t('Run `composer require` in order to download the required packages');
      $this->batchContext['sandbox']['current_step'] = 'composer_require';
      $this->batchContext['sandbox']['finished'] = 0.1;

      return $this;
    }

    switch ($this->batchContext['sandbox']['current_step']) {
      case 'composer_require':
        $this->doItComposerRequire();
        drupal_flush_all_caches();

        $this->batchContext['message'] = $this->t('Code generation');
        $this->batchContext['sandbox']['current_step'] = 'code';
        $this->batchContext['sandbox']['finished'] = 0.3;
        break;

      case 'code':
        $this
          ->doItDefinition()
          ->doItAnnotation()
          ->doItDefinitionComparer()
          ->doItManager()
          ->doItParamConverter();
        drupal_flush_all_caches();

        $this->batchContext['message'] = $this->t('Finished');
        $this->batchContext['sandbox']['current_step'] = 'finished';
        $this->batchContext['sandbox']['finished'] = 1.0;
        break;

      case 'finished':
        $this->batchContext['sandbox']['finished'] = 1.0;
        break;
    }

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItDefinition(): static {
    $conf = $this->getConfiguration();

    $this->fs->mkdir(Path::getDirectory($conf['definition']['filePath']));
    $this->fs->dumpFile(
      $conf['definition']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/definition.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['definition']['filePath']);

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItAnnotation(): static {
    $conf = $this->getConfiguration();

    $this->fs->mkdir(Path::getDirectory($conf['annotation']['filePath']));
    $this->fs->dumpFile(
      $conf['annotation']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/annotation.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['annotation']['filePath']);

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItDefinitionComparer(): static {
    $conf = $this->getConfiguration();

    $this->fs->mkdir(Path::getDirectory($conf['definitionComparer']['filePath']));
    $this->fs->dumpFile(
      $conf['definitionComparer']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/definition_comparer.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['definitionComparer']['filePath']);

    $filePath = Path::join(
      $conf['moduleDir'],
      "{$conf['module']}.services.yml",
    );
    $this->utils->ymlFileReplace(
      $filePath,
      [
        $conf['definitionComparer']['service']['id'] => $conf['definitionComparer']['service']['definition'],
      ],
      ['services'],
    );
    $this->messageFilesystemEntryUpdate($filePath);

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItManager(): static {
    $conf = $this->getConfiguration();

    $this->fs->mkdir(Path::getDirectory($conf['pluginInterface']['filePath']));
    $this->fs->dumpFile(
      $conf['pluginInterface']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/plugin_interface.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['pluginInterface']['filePath']);

    $this->fs->mkdir(Path::getDirectory($conf['managerInterface']['filePath']));
    $this->fs->dumpFile(
      $conf['managerInterface']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/manager_interface.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['managerInterface']['filePath']);

    $this->fs->mkdir(Path::getDirectory($conf['manager']['filePath']));
    $this->fs->dumpFile(
      $conf['manager']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/manager.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['manager']['filePath']);

    $filePath = Path::join(
      $conf['moduleDir'],
      "{$conf['module']}.services.yml",
    );
    $this->utils->ymlFileReplace(
      $filePath,
      [
        $conf['manager']['service']['id'] => $conf['manager']['service']['definition'],
      ],
      ['services'],
    );
    $this->messageFilesystemEntryUpdate($filePath);

    return $this;
  }

  /**
   * @throws \Twig\Error\Error
   */
  protected function doItParamConverter(): static {
    $conf = $this->getConfiguration();

    $this->fs->mkdir(Path::getDirectory($conf['paramConverter']['filePath']));
    $this->fs->dumpFile(
      $conf['paramConverter']['filePath'],
      $this->twig->render(
        '@devel_wizard/spell/plugin_manager/param_converter.php.twig',
        $conf,
      ),
    );
    $this->messageFilesystemEntryCreate($conf['paramConverter']['filePath']);

    $filePath = Path::join(
      $conf['moduleDir'],
      "{$conf['module']}.services.yml",
    );
    $this->utils->ymlFileReplace(
      $filePath,
      [
        $conf['paramConverter']['service']['id'] => $conf['paramConverter']['service']['definition'],
      ],
      ['services'],
    );
    $this->messageFilesystemEntryUpdate($filePath);

    return $this;
  }

}

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

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