ppf-1.2.x-dev/src/Form/PPFConfigurationForm.php

src/Form/PPFConfigurationForm.php
<?php

namespace Drupal\ppf\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\Extension\ThemeExtensionList;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\ppf\PreprocessorFiles;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Provides a configuration form for the Preprocessor Files module.
 *
 * @package Drupal\ppf\Form
 *
 * @noinspection PhpUnused
 */
class PPFConfigurationForm extends ConfigFormBase {

  /**
   * The FORM ID.
   *
   * @var string
   */
  public const FORM_ID = 'preprocessor_files_configuration_form';

  /**
   * The Theme Manager service injected through DI.
   *
   * @var \Drupal\Core\Theme\ThemeManagerInterface
   */
  protected ThemeManagerInterface $themeManager;

  /**
   * The Theme Extension List service injected through DI.
   *
   * @var \Drupal\Core\Extension\ThemeExtensionList
   */
  protected ThemeExtensionList $themeExtensionList;

  /**
   * The Module Extension List service injected through DI.
   *
   * @var \Drupal\Core\Extension\ModuleExtensionList
   */
  protected ModuleExtensionList $moduleExtensionList;

  /**
   * The File System service injected through DI.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected FileSystemInterface $fileSystem;

  /**
   * Constructs a new EntityListBuilder object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   ConfigFactory service.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $themeManager
   *   Theme Manager service.
   * @param \Drupal\Core\Extension\ThemeExtensionList $themeExtensionList
   *   Theme Extension List service.
   * @param \Drupal\Core\Extension\ModuleExtensionList $moduleExtensionList
   *   Module Extension List service.
   * @param \Drupal\Core\File\FileSystemInterface $fileSystem
   *   File System service.
   */
  public function __construct(
    ConfigFactoryInterface $configFactory,
    ThemeManagerInterface $themeManager,
    ThemeExtensionList $themeExtensionList,
    ModuleExtensionList $moduleExtensionList,
    FileSystemInterface $fileSystem
  ) {
    parent::__construct($configFactory);
    $this->themeManager = $themeManager;
    $this->themeExtensionList = $themeExtensionList;
    $this->moduleExtensionList = $moduleExtensionList;
    $this->fileSystem = $fileSystem;
  }

  /**
   * {@inheritdoc}
   *
   * @noinspection PhpParamsInspection
   */
  public static function create(ContainerInterface $container) : PPFConfigurationForm {
    return new static(
      $container->get('config.factory'),
      $container->get('theme.manager'),
      $container->get('extension.list.theme'),
      $container->get('extension.list.module'),
      $container->get('file_system'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return self::FORM_ID;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() : array {
    return [
      PreprocessorFiles::CONFIG_ID,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) : array {
    // Set this for easier organization of form values later.
    $form['#tree'] = TRUE;

    // Get the current configurations.
    $preprocessorFilesExtension = $this->config(PreprocessorFiles::CONFIG_ID)
      ->get(PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION)
      ?? PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT;

    // Get system theme config.
    $systemThemeConfig = $this->configFactory->get('system.theme');
    $defaultTheme = $systemThemeConfig->get('default');
    $defaultThemePath = $this->themeExtensionList->getPath($defaultTheme);
    $preprocessorFilesDirectoryPath = $defaultThemePath . '/' . PreprocessorFiles::PREPROCESSOR_FILES_DIRECTORY;

    // If the Preprocessor Files Directory doesn't exist, we throw a warning.
    if (!file_exists($preprocessorFilesDirectoryPath)) {
      $this->messenger()->addWarning($this->t("The <code>@directory</code> directory does not exist in your site's default theme (<code>@defaultTheme</code>). <br>Use the button below to generate the directory and start creating preprocessor files.", [
        '@defaultTheme' => $defaultTheme,
        '@directory' => PreprocessorFiles::PREPROCESSOR_FILES_DIRECTORY,
      ]));

      $form['generate'] = [
        '#type' => 'submit',
        '#name' => 'generate',
        '#value' => $this->t('Generate Directory'),
        '#attributes' => [
          'class' => [
            'button',
            'button--primary',
          ],
        ],
        '#submit' => [
          '::generateDirectory',
        ],
      ];
    }

    $form[PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Preprocessor Files Extension'),
      '#description'   => $this->t('Customize the file extension to search for.'),
      '#default_value' => !empty($preprocessorFilesExtension) ? $preprocessorFilesExtension : PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT,
    ];

    // Return the form with all necessary fields.
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) : void {
    // Retrieve the configuration.
    $values = $form_state->getValues();

    // Save configurations.
    $this->configFactory->getEditable(PreprocessorFiles::CONFIG_ID)
      ->set(PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION, $values[PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION])
      ->save();

    // Default submission handler.
    parent::submitForm($form, $form_state);
  }

  /**
   * Custom submission handler to generate directory.
   *
   * @param array $form
   *   Render array of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function generateDirectory(array &$form, FormStateInterface $form_state) : void {
    $systemThemeConfig = $this->configFactory->get('system.theme');
    $defaultTheme = $systemThemeConfig->get('default');
    $defaultThemePath = $this->themeExtensionList->getPath($defaultTheme);
    $directoryName = PreprocessorFiles::PREPROCESSOR_FILES_DIRECTORY;
    $directoryPath = $defaultThemePath . '/' . $directoryName;
    $modulePath = $this->moduleExtensionList->getPath('ppf');
    $blueprints = $modulePath . '/blueprints/theme/' . PreprocessorFiles::PREPROCESSOR_FILES_DIRECTORY;

    // We'll use the Symfony file system here.
    $symfonyFs = new Filesystem();

    // Copy our blueprints and create a starter directory.
    $symfonyFs->mirror($blueprints, $directoryPath);

    // Get configured file extension.
    $extension = $this->configFactory
      ->get(PreprocessorFiles::CONFIG_ID)
      ->get(PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION)
      ?? PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT;

    // If the extension is different, we rename the resulting example file.
    if ($extension !== PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT) {
      $symfonyFs->copy(
        $blueprints . '/.HOOK' . PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT,
        $directoryPath . '/.HOOK' . $extension,
      );
      $symfonyFs->remove($directoryPath . '/.HOOK' . PreprocessorFiles::CONFIG__PREPROCESSOR_FILES_EXTENSION__DEFAULT);
    }

    $this->messenger()->addMessage(
      $this->t(
        "
                The <code>@directory</code> directory has been created in your site's default theme (<code>@defaultTheme</code>).<br>
                An example file called <code>.HOOK.preprocess.php</code> has been placed in the directory. You can use this as an example!<br>
                Also, please note that dotfiles are ignored. When creating your own Preprocessor Files, omit the dot (.) at the start of the filename.<br>
                Happy Preprocessing!
              ",
        [
          '@defaultTheme' => $defaultTheme,
          '@directory' => $directoryName,
        ]
      )
    );
  }

}

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

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