a12s-1.0.0-beta7/modules/page_context/src/Form/PathEdit.php

modules/page_context/src/Form/PathEdit.php
<?php

namespace Drupal\a12s_page_context\Form;

use Drupal\a12s_page_context\Entity\PageContextForm;
use Drupal\a12s_page_context\PageContextManagerInterface;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Database\Connection;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
use Drupal\system\Plugin\Condition\RequestPath;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Displays the path edit form.
 */
class PathEdit extends FormBase {

  /**
   * Constructs a PathEdit object.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   * @param \Drupal\a12s_page_context\PageContextManagerInterface $contextFormManager
   *   The Page Context Manager service.
   */
  public function __construct(
    protected Connection $connection,
    protected PageContextManagerInterface $contextFormManager
  ) {}

  /**
   * {@inheritdoc}
   * @noinspection PhpParamsInspection
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('database'),
      $container->get('a12s_page_context.manager')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $path_key = NULL): array {
    $configuration = [];

    if ($path_key) {
      $firstRecord = $this->connection->select('a12s_page_context_record')
        ->fields('a12s_page_context_record', ['settings'])
        ->condition('key', $path_key)
        ->execute()
        ->fetchField();

      if ($firstRecord) {
        $configuration = @unserialize($firstRecord) ?: [];
      }
    }

    if (!$condition = $this->getRequestPathConditionPlugin($configuration)) {
      throw new NotFoundHttpException();
    }

    $form = $condition->buildConfigurationForm($form, $form_state);
    PageContextForm::alterForm('path', ['path_key' => $path_key], $form, $form_state);

    if (empty($form['a12s_page_context'])) {
      $this->messenger()->addWarning($this > t('There is no forms whose path plugin is enabled.'));
    }
    else {
      $form['actions'] = ['#type' => 'actions'];

      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#submit' => [
          '::submitForm',
          [PageContextForm::class, 'saveRecord'],
        ],
      ];

      if (!empty($path_key)) {
        $deleteUrl = Url::fromRoute('entity.a12s_page_context_form.path_delete_form', ['path_key' => $path_key]);

        if ($this->getRequest()->query->has('destination')) {
          $query = $deleteUrl->getOption('query');
          $query['destination'] = $this->getRequest()->query->get('destination');
          $deleteUrl->setOption('query', $query);
        }

        $form['actions']['delete'] = [
          '#type' => 'link',
          '#title' => $this->t('Delete'),
          '#url' => $deleteUrl,
          '#attributes' => [
            'class' => ['button', 'button--danger'],
          ],
        ];
      }
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state): void {
    parent::validateForm($form, $form_state);
    $this->getRequestPathConditionPlugin()->validateConfigurationForm($form, $form_state);

    // @todo search for records which have the same hash for the "key" value,
    //   but not the same ID. If we find some matching records, should we
    //   display an error message? Currently the previous path is overridden by
    //   the new one.
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->getRequestPathConditionPlugin()->submitConfigurationForm($form, $form_state);

    $keyParts = [
      'pages' => $form_state->getValue('pages'),
      'negate' => $form_state->getValue('negate'),
    ];

    foreach ($form_state->getValue('a12s_page_context', []) as $key => $values) {
      $values['key'] = hash('md5', serialize($keyParts));
      $values['settings'] = $keyParts;
      $form_state->setValue(['a12s_page_context', $key], $values);
    }

    $form_state->setRedirect('entity.a12s_page_context_form.paths_overview');
    $this->messenger()->addStatus($this->t('The path configuration has been saved.'));
  }

  /**
   * Get a condition plugin instance.
   *
   * @param array $configuration
   *   The plugin configuration.
   *
   * @return \Drupal\system\Plugin\Condition\RequestPath|null
   *   The plugin instance, or NULL.
   */
  protected function getRequestPathConditionPlugin(array $configuration = []): ?RequestPath {
    try {
      $conditionManager = \Drupal::service('plugin.manager.condition');
      return $conditionManager->createInstance('request_path', $configuration);
    }
    catch (PluginException $e) {
      Error::logException(\Drupal::logger('a12s_page_context'), $e);
      return NULL;
    }
  }

}

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

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