ispim-1.0.x-dev/src/PreviewImage/SettingsForm.php

src/PreviewImage/SettingsForm.php
<?php

declare(strict_types=1);

namespace Drupal\ispim\PreviewImage;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\ConfigTarget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\ispim\ConfigObjectFormExportMessageTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SettingsForm extends ConfigFormBase {

  use ConfigObjectFormExportMessageTrait;

  protected string $entityTypeId = 'ispim_preview_image';

  /**
   * {@inheritdoc}
   *
   * @phpstan-return static
   */
  public static function create(ContainerInterface $container) {
    // @phpstan-ignore-next-line
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('entity_type.manager'),
      $container->get('entity_field.manager'),
      $container->get('language_manager'),
      $container->get('stream_wrapper_manager'),
      $container->get('entity.definition_update_manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    TypedConfigManagerInterface $typedConfigManager,
    protected EntityTypeManagerInterface $entityTypeManager,
    protected EntityFieldManagerInterface $entityFieldManager,
    protected LanguageManagerInterface $languageManager,
    protected StreamWrapperManagerInterface $streamWrapperManager,
    protected EntityDefinitionUpdateManagerInterface $entityDefinitionUpdateManager,
  ) {
    parent::__construct($config_factory, $typedConfigManager);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'ispim_ispim_preview_image_settings_form';
  }

  /**
   * {@inheritdoc}
   *
   * @phpstan-return array<string>
   */
  protected function getEditableConfigNames(): array {
    return [
      'ispim.ispim_preview_image.settings',
    ];
  }

  /**
   * {@inheritdoc}
   *
   * @phpstan-param array<string, mixed> $form
   *
   * @phpstan-return array<string, mixed>
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form = parent::buildForm($form, $form_state);

    $configName = $this->getEditableConfigNames()[0];

    $baseFieldDefinitions = $this
      ->entityFieldManager
      ->getBaseFieldDefinitions($this->entityTypeId);
    $imageFieldDefinition = $baseFieldDefinitions['image'];

    $form['langcode'] = [
      '#config_target' => "$configName:langcode",
      '#type' => 'language_select',
      '#title' => $this->t('Language'),
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
      '#default_value' => $this->languageManager->getDefaultLanguage()->getId(),
      '#access' => FALSE,
    ];

    $form['help'] = [
      '#config_target' => "$configName:help",
      '#type' => 'textarea',
      '#title' => $this->t('Help'),
    ];

    $isStorageSettingsLocked = $this->numOfContent() > 0;
    $form['image'] = [
      '#type' => 'details',
      '#tree' => TRUE,
      '#title' => $this->t('Image'),
      '#open' => TRUE,

      // @see \Drupal\file\Plugin\Field\FieldType\FileItem::storageSettingsForm().
      'storage_settings' => [
        '#type' => 'details',
        '#tree' => TRUE,
        '#title' => $this->t('Storage settings'),
        '#open' => TRUE,
        '#description' => '<p>' . $this->t(
          'These settings apply to the %field field everywhere it is used. Some also impact the way that data is stored and cannot be changed once data has been created.',
          [
            '%field' => $imageFieldDefinition->getLabel(),
          ],
        ) . '</p>',

        'uri_scheme' => [
          '#config_target' => "$configName:image.storage_settings.uri_scheme",
          '#type' => 'radios',
          '#title' => $this->t('Upload destination'),
          '#options' => $this->getSchemeOptions(),
          '#description' => $this->t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
          '#disabled' => $isStorageSettingsLocked,
        ],
      ],
    ];

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

      'enabled' => [
        '#config_target' => "$configName:revision.enabled",
        '#type' => 'checkbox',
        '#title' => $this->t('Enabled'),
        '#return_value' => 1,
      ],
    ];

    $listBuilderName = $this->parentsToName(['listBuilder', 'renderer']);

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

      'renderer' => [
        '#config_target' => new ConfigTarget(
          configName: $configName,
          propertyPath: 'listBuilder.renderer',
        ),
        '#type' => 'radios',
        '#required' => TRUE,
        '#title' => $this->t('Renderer'),
        '#options' => [
          'default' => $this->t('Default'),
          'viewMode' => $this->t('View Mode'),
        ],
      ],

      'config' => [
        '#tree' => TRUE,

        'viewMode' => [
          '#tree' => TRUE,
          '#type' => 'fieldset',
          '#states' => [
            'visible' => [
              ":input[name='$listBuilderName']" => ['value' => 'viewMode'],
            ],
          ],
          // @todo Validate.
          'id' => [
            '#config_target' => new ConfigTarget(
              configName: $configName,
              propertyPath: 'listBuilder.config.viewMode.id',
            ),
            '#type' => 'select',
            '#title' => $this->t('View mode'),
            '#empty_option' => $this->t('- Select -'),
            '#options' => $this->getListBuilderViewModeOptions(),
            '#states' => [
              'required' => [
                ":input[name='$listBuilderName']" => ['value' => 'viewMode'],
              ],
            ],
          ],
        ],

        'default' => [
          '#tree' => TRUE,
          '#type' => 'fieldset',
          '#states' => [
            'visible' => [
              ":input[name='$listBuilderName']" => ['value' => 'default'],
            ],
          ],
          // @todo Validate.
          'imageStyle' => [
            '#config_target' => new ConfigTarget(
              configName: $configName,
              propertyPath: 'listBuilder.config.default.imageStyle',
            ),
            '#type' => 'select',
            '#title' => $this->t('Image Style'),
            '#empty_option' => $this->t('- Select -'),
            '#options' => $this->getListBuilderDefaultImageStyleOptions(),
            '#states' => [
              'required' => [
                ":input[name='$listBuilderName']" => ['value' => 'default'],
              ],
            ],
          ],
        ],
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @phpstan-param array<string, mixed> $form
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    // @todo Check if the uri_scheme changed and clear the cache.
    parent::submitForm($form, $form_state);
    $this->emitExportUriMessages();
  }

  /**
   * @phpstan-return int<0, max>
   */
  protected function numOfContent(): int {
    /* @noinspection PhpUnhandledExceptionInspection */
    return (int) $this
      ->entityTypeManager
      ->getStorage($this->entityTypeId)
      ->getQuery()
      ->accessCheck(FALSE)
      ->count()
      ->execute();
  }

  /**
   * @return array<string, string|\Stringable>
   */
  protected function getSchemeOptions(): array {
    return $this
      ->streamWrapperManager
      ->getNames(StreamWrapperInterface::WRITE_VISIBLE);
  }

  /**
   * @return array<string, string|\Drupal\Core\StringTranslation\TranslatableMarkup>
   */
  protected function getListBuilderViewModeOptions(): array {
    $options = [];

    /* @noinspection PhpUnhandledExceptionInspection */
    /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $viewModeStorage */
    $viewModeStorage = $this->entityTypeManager->getStorage('entity_view_mode');
    /** @var array<string, \Drupal\Core\Entity\EntityViewModeInterface> $viewModes */
    $viewModes = $viewModeStorage->loadByProperties([
      'targetEntityType' => 'ispim_preview_image',
    ]);
    foreach ($viewModes as $viewMode) {
      $shortId = preg_replace('/^.*?\./', '', (string) $viewMode->id());
      $options[$shortId] = $viewMode->label();
    }

    return $options;
  }

  /**
   * @return array<string|\Stringable|\Drupal\Core\StringTranslation\TranslatableMarkup>
   */
  protected function getListBuilderDefaultImageStyleOptions(): array {
    $options = [];

    /* @noinspection PhpUnhandledExceptionInspection */
    /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $imageStyleStorage */
    $imageStyleStorage = $this->entityTypeManager->getStorage('image_style');
    foreach ($imageStyleStorage->loadMultiple() as $imageStyle) {
      $options[$imageStyle->id()] = $imageStyle->label();
    }

    return $options;
  }

  /**
   * @param array<string> $parents
   *
   * @return string
   */
  protected function parentsToName(array $parents): string {
    $name = array_shift($parents);

    return !$parents
      ? $name
      : $name . '[' . implode('][', $parents) . ']';
  }

}

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

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