You are here

public function TagForm::validateForm in Extensible BBCode 8.3

Same name and namespace in other branches
  1. 4.0.x src/Form/TagForm.php \Drupal\xbbcode\Form\TagForm::validateForm()

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/TagForm.php, line 127

Class

TagForm
Base form for creating and editing custom tags.

Namespace

Drupal\xbbcode\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) : void {
  parent::validateForm($form, $form_state);

  /** @var \Drupal\xbbcode\Entity\TagInterface $tag */
  $tag = $this->entity;

  // Set up a mock parser and do a practice run with this tag.
  $called = FALSE;
  $processor = new CallbackTagProcessor(static function () use (&$called) {
    $called = TRUE;
  });
  $parser = new XBBCodeParser([
    $tag
      ->getName() => $processor,
  ]);
  $sample = str_replace('{{ name }}', $tag
    ->getName(), $tag
    ->getSample());
  $tree = $parser
    ->parse($sample);
  try {
    $template = $this->twig
      ->load(EntityTagPlugin::TEMPLATE_PREFIX . $tag
      ->getTemplateCode());
    $processor
      ->setProcess(static function ($tag) use ($template, &$called) {
      $called = TRUE;
      return $template
        ->render([
        'tag' => $tag,
      ]);
    });
  } catch (TwigError $exception) {
    $error = str_replace(EntityTagPlugin::TEMPLATE_PREFIX, '', $exception
      ->getMessage());
    $form_state
      ->setError($form['template_code'], $this
      ->t('The template could not be compiled: @error', [
      '@error' => $error,
    ]));
  }
  try {
    $tree
      ->render();
  } catch (Throwable $exception) {
    $form_state
      ->setError($form['template_code'], $this
      ->t('An error occurred while rendering the template: @error', [
      '@error' => $exception
        ->getMessage(),
    ]));
  }
  if (!$called) {
    $form_state
      ->setError($form['sample'], $this
      ->t('The sample code should contain a valid example of the tag.'));
  }
}