improvements-2.x-dev/modules/improvements_taxonomy/src/Plugin/Condition/TermDepth.php

modules/improvements_taxonomy/src/Plugin/Condition/TermDepth.php
<?php

namespace Drupal\improvements_taxonomy\Plugin\Condition;

use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Condition\Attribute\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Render\Element\Checkboxes;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\taxonomy\TermInterface;

#[Condition(
  id: 'term_depth',
  label: new TranslatableMarkup('Term depth'),
  context_definitions: [
    'taxonomy_term' => new EntityContextDefinition(
      data_type: 'entity:taxonomy_term',
      label: new TranslatableMarkup('Taxonomy term'),
    ),
  ],
)]
class TermDepth extends ConditionPluginBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return ['depth' => []] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $form['depth'] = [
      '#type' => 'checkboxes',
      '#title' => $this->pluginDefinition['label'],
      '#options' => [
        0 => 0,
        1 => 1,
        2 => 2,
        3 => 3,
        4 => 4,
        5 => 5,
      ],
      '#default_value' => $this->configuration['depth'],
    ];

    return parent::buildConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
    $this->configuration['depth'] = Checkboxes::getCheckedCheckboxes($form_state->getValue('depth'));
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function summary(): MarkupInterface {
    return $this->t('Term depth is @depth', ['@depth' => implode(', ', $this->configuration['depth'])]);
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate(): bool {
    if (empty($this->configuration['depth']) && !$this->isNegated()) {
      return TRUE;
    }
    $term = $this->getContextValue('taxonomy_term'); /** @var TermInterface $term */
    $term_depth = $term->get('stored_depth')->value;
    return in_array($term_depth, $this->configuration['depth']);
  }

}

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

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