Skip to content
Snippets Groups Projects

Issue #3352393: New condition: Contains for lists

Closed Jürgen Haas requested to merge issue/eca-3352393:3352393-new-condition-contains into 1.2.x
1 file
+ 92
0
Compare changes
  • Side-by-side
  • Inline
<?php
namespace Drupal\eca_base\Plugin\ECA\Condition;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\TypedData;
use Drupal\eca\Plugin\ECA\Condition\ConditionBase;
/**
* ECA condition plugin for numerically comparing number of list items.
*
* @EcaCondition(
* id = "eca_list_contains",
* label = @Translation("List contains item"),
* description = @Translation("Condition to verify if a list contains a given item.")
* )
*/
class ListContains extends ConditionBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'list_token_name' => '',
'value' => '',
] + parent::defaultConfiguration();
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
$form['list_token_name'] = [
'#type' => 'textfield',
'#title' => $this->t('List token name'),
'#default_value' => $this->configuration['list_token_name'],
'#weight' => -90,
'#description' => $this->t('The name of the token which contains the list.'),
];
$form['value'] = [
'#type' => 'textfield',
'#title' => $this->t('Value'),
'#default_value' => $this->configuration['value'],
'#weight' => -80,
'#description' => $this->t('The value that should be verified against the list. This field supports tokens'),
];
return parent::buildConfigurationForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
parent::submitConfigurationForm($form, $form_state);
$this->configuration['list_token_name'] = $form_state->getValue('list_token_name');
$this->configuration['value'] = $form_state->getValue('value');
}
/**
* {@inheritdoc}
*/
public function evaluate(): bool {
$result = FALSE;
$list = $this->tokenServices->getTokenData($this->configuration['list_token_name']);
if (is_iterable($list)) {
$value = $this->tokenServices->replaceClear($this->configuration['value']);
foreach ($list as $item) {
if (is_scalar($item)) {
if ((string) $item === (string) $value) {
$result = TRUE;
break;
}
}
elseif ($item instanceof TypedData) {
if ($item->getString() === (string) $value) {
$result = TRUE;
break;
}
}
elseif ($item === $value) {
$result = TRUE;
break;
}
}
}
return $this->negationCheck($result);
}
}
Loading