You are here

public function OneOfSeveralValidationRule::validate in Field Validation 8

Overrides FieldValidationRuleBase::validate

File

src/Plugin/FieldValidationRule/OneOfSeveralValidationRule.php, line 79

Class

OneOfSeveralValidationRule
OneOfSeveralValidationRule

Namespace

Drupal\field_validation\Plugin\FieldValidationRule

Code

public function validate($params) {
  $flag = FALSE;

  /** @var ConfigurableFieldValidationRuleInterface $rule */
  $rule = $params['rule'] ?? NULL;

  /** @var \Drupal\field_validation\Entity\FieldValidationRuleSet $ruleset */
  $ruleset = $params['ruleset'] ?? NULL;

  /** @var \Drupal\Core\TypedData\Validation\ExecutionContext $context */
  $context = $params['context'];
  $field_values = $this
    ->getFieldColumnValue($params['items'], $rule->column);
  $field_values = array_flip($field_values);
  if (count($field_values) > 0) {
    $flag = TRUE;
  }
  if (!$flag) {
    $group_name = $rule->configuration['data'];

    /** @var \Drupal\field_validation\FieldValidationRuleInterface $other_group_rule */
    foreach ($ruleset
      ->getFieldValidationRules() as $other_group_rule) {
      if ($other_group_rule
        ->getPluginId() !== $rule
        ->getPluginId() || $other_group_rule
        ->getUuid() === $rule
        ->getUuid()) {
        continue;
      }
      $configuration = $other_group_rule
        ->getConfiguration();
      if ($configuration['data']['data'] !== $group_name) {
        continue;
      }

      /** @var \Drupal\node\Entity\Node $object */
      $entity = $context
        ->getRoot()
        ->getValue();
      $other_items = $entity->{$other_group_rule
        ->getFieldName()};
      $other_field_values = $this
        ->getFieldColumnValue($other_items, $other_group_rule
        ->getColumn());
      $other_field_values = array_flip($other_field_values);
      if (count($other_field_values) > 0) {
        $flag = TRUE;
        break;
      }
    }
  }
  if (!$flag) {
    $context
      ->addViolation($rule
      ->getErrorMessage());
  }
  return TRUE;
}