picture_everywhere-1.0.0/src/Form/SettingsForm.php

src/Form/SettingsForm.php
<?php

namespace Drupal\picture_everywhere\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\picture_everywhere\Preprocess;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Settings form for Picture Everywhere.
 */
class SettingsForm extends ConfigFormBase {

  public const HTML_TAGS_FOR_T = [
    '@img_tag'     => '<img>',
    '@picture_tag' => '<picture>',
    '@source_tag'  => '<source>',
  ];

  public const WEBP_MODULE_URL = 'https://www.drupal.org/project/webp';

  /**
   * The module handler.
   */
  protected ModuleHandlerInterface $moduleHandler;

  /**
   * The theme handler.
   */
  protected ThemeHandlerInterface $themeHandler;

  /**
   * Constructs the Picture Everywhere settings form.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    TypedConfigManagerInterface $typed_config_manager,
    ModuleHandlerInterface $module_handler,
    ThemeHandlerInterface $theme_handler,
  ) {
    parent::__construct($config_factory, $typed_config_manager);

    $this->moduleHandler = $module_handler;
    $this->themeHandler = $theme_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('module_handler'),
      $container->get('theme_handler')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return [
      'picture_everywhere.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->configFactory->get('picture_everywhere.settings');

    $form['themes'] = [
      '#type'        => 'fieldset',
      '#tree'        => TRUE,
      '#title'       => $this->t('Themes'),
      '#description' => $this->t('Choose the theme(s) Picture Everywhere should be active for.'),
    ];
    $enabled_themes = $config->getOriginal('themes', FALSE) ?: [];
    foreach ($this->themeHandler->listInfo() as $theme_name => $theme) {
      $form['themes'][$theme_name] = [
        '#type'          => 'checkbox',
        '#title'         => $theme->info['name'] ?? $theme_name,
        '#default_value' => in_array($theme_name, $enabled_themes, TRUE),
      ];
    }

    $form['output'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];

    $form['output']['img_tag_attributes'] = [
      '#type'  => 'textarea',
      '#title' => $this->t('@img_tag tag attributes', self::HTML_TAGS_FOR_T),
      '#description' => $this->t(
        'Enter attributes that should be placed on the @img_tag tag instead of the @picture_tag tag. One per line.<br>The following attributes will always go on @img_tag no matter what, and do not need to be listed here:<br>@hardcoded_tags',
        self::HTML_TAGS_FOR_T + [
          '@hardcoded_tags' => Markup::create('<ul><li>' . implode('</li><li>', Preprocess::ALWAYS_IMG_TAG_ATTRS) . '</li></ul>'),
        ]
      ),
      '#default_value' => implode("\n", $config->getOriginal('output.img_tag_attributes', FALSE) ?: []),
      '#attributes' => [
        'spellcheck' => 'false',
      ],
    ];

    $form['output']['webp'] = [
      '#type'    => 'fieldset',
      '#tree'    => TRUE,
      '#title'   => $this->t('WebP'),

      'auto_webp_source' => [
        '#type'          => 'checkbox',
        '#title'         => $this->t('Automatically add Webp @source_tag', self::HTML_TAGS_FOR_T),
        '#description'   => $this->t(
          '<strong>Intended for use with the <a href=":webp_url" target="_blank">Webp</a> module, which can be used to enable autogeneration of these URLs.</strong><br>Adds an additional image source tag with the file extension changed to .webp, if the original image has the JPG or PNG file extension.<br>Note that this is only necessary if your image styles do not convert to WebP. That is, if PNG and JPG derivatives are being served on this site. You may not need to serve JPG and PNG any longer if you do not support older browsers such as Internet Explorer.',
          [':webp_url' => self::WEBP_MODULE_URL],
        ),
        '#default_value' => $config->getOriginal('output.webp.auto_webp_source', FALSE),
      ],
    ];

    if (!$this->moduleHandler->moduleExists('webp')) {
      $form['output']['webp']['webp_module_not_installed'] = [
        '#type' => 'container',

        'warning_message' => [
          '#theme' => 'status_messages',
          '#message_list' => [
            'warning' => [
              $this->t(
                'Picture Everywhere does <em>not</em> provide any functionality for generation of these additional image URLs. The <a href=":webp_url" target="_blank">WebP module</a> should be installed to provide generation.',
                [':webp_url' => self::WEBP_MODULE_URL],
              ),
            ],
          ],
          '#status_headings' => [
            'status'  => $this->t('Status message'),
            'error'   => $this->t('Error message'),
            'warning' => $this->t('Warning message'),
          ],
        ],
      ];

      // Add #states once drupal selectors are determined.
      $form['output']['webp']['#after_build'][] = [
        self::class,
        'processWebpFieldset',
      ];
    }
    elseif ($this->moduleHandler->moduleExists('responsive_image')) {
      $form['output']['webp']['responsive_image_warning'] = [
        '#theme' => 'status_messages',
        '#message_list' => [
          'warning' => [
            $this->t(
              'This functionality only applies to single-source images. Multiple-source image styles from the Responsive Image module are not supported.',
              [':webp_url' => self::WEBP_MODULE_URL],
            ),
          ],
        ],
        '#status_headings' => [
          'status'  => $this->t('Status message'),
          'error'   => $this->t('Error message'),
          'warning' => $this->t('Warning message'),
        ],
      ];
    }

    $build = parent::buildForm($form, $form_state);

    return $build;
  }

  /**
   * WebP settings #after_build callback.
   */
  public static function processWebpFieldset(array $element, FormStateInterface $form_state): array {
    if (!empty($element['auto_webp_source']['#attributes']['data-drupal-selector'])) {
      $element['webp_module_not_installed']['#states'] = [
        'visible' => [
          '[data-drupal-selector="' . $element['auto_webp_source']['#attributes']['data-drupal-selector'] . '"]' => [
            'checked' => TRUE,
          ],
        ],
      ];
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state): void {
    $allowed_img_tag_attrs = $form_state->getValue([
      'output',
      'img_tag_attributes',
    ]) ?? '';
    $allowed_img_tag_attrs = preg_split('/\s*\R\s*/', $allowed_img_tag_attrs, 0, PREG_SPLIT_NO_EMPTY);
    $allowed_img_tag_attrs = array_unique($allowed_img_tag_attrs);
    foreach ($allowed_img_tag_attrs as $tag_key => &$allowed_attr) {
      $allowed_attr = strtolower($allowed_attr);

      // Remove any tags that are hardcoded to go on the image.
      if (in_array($allowed_attr, Preprocess::ALWAYS_IMG_TAG_ATTRS, TRUE)) {
        unset($allowed_img_tag_attrs[$tag_key]);
      }
    }
    $allowed_img_tag_attrs = array_values($allowed_img_tag_attrs);
    sort($allowed_img_tag_attrs);
    $form_state->setValue(['output', 'img_tag_attributes'], $allowed_img_tag_attrs);

    foreach ($allowed_img_tag_attrs as $allowed_img_attr) {
      if (!preg_match('/^[^\t\n\f \/<>"\'=]+$/', $allowed_img_attr)) {
        $form_state->setErrorByName(
          'output][img_tag_attributes',
          $this->t(
            '"@invalid_tag" is not a valid HTML attribute.',
            ['@invalid_tag' => $allowed_img_attr]
          )
        );
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $data = [
      'themes' => array_keys(array_filter($form_state->getValue('themes'))),
      'output' => [
        'img_tag_attributes' => $form_state->getValue([
          'output',
          'img_tag_attributes',
        ]),
        'webp'               => $form_state->getValue(['output', 'webp']),
      ],
      'integrations' => $form_state->getValue('integrations'),
    ];

    $this->config('picture_everywhere.settings')
      ->setData($data)
      ->save();

    parent::submitForm($form, $form_state);
  }

}

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

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