You are here

public static function Registrants::validateRegisterable in RNG - Events and Registrations 3.x

Same name and namespace in other branches
  1. 8.2 src/Element/Registrants.php \Drupal\rng\Element\Registrants::validateRegisterable()
  2. 8 src/Element/Registrants.php \Drupal\rng\Element\Registrants::validateRegisterable()

Validate whether all existing registrants are register-able.

An identity may have been registered by another registration while it is also stored in the state of another registration.

File

src/Element/Registrants.php, line 708

Class

Registrants
Provides a form element for a registrant and person association.

Namespace

Drupal\rng\Element

Code

public static function validateRegisterable(&$element, FormStateInterface $form_state, &$complete_form) {
  $utility = new RegistrantsElement($element, $form_state);

  // Add existing registrants to whitelist.
  foreach ($element['#default_value'] as $existing_registrant) {
    $identity = $existing_registrant
      ->getIdentity();
    if ($identity) {
      $utility
        ->addWhitelistExisting($identity);
    }
  }

  /** @var \Drupal\rng\Entity\RegistrantInterface[] $registrants */
  $registrants = $element['#value'];
  $whitelisted = $utility
    ->getWhitelistExisting();
  $identities = [];
  foreach ($registrants as $registrant) {
    $identity = $registrant
      ->getIdentity();
    if ($identity) {
      $entity_type = $identity
        ->getEntityTypeId();
      $id = $identity
        ->id();

      // Check if identity can skip existing revalidation. This needs to be done
      // when the identity was created by this element.
      if (!isset($whitelisted[$entity_type][$id])) {
        $identities[$entity_type][$id] = $identity
          ->label();
      }
    }
  }

  /** @var \Drupal\rng\EventManagerInterface $event_manager */
  $event_manager = \Drupal::service('rng.event_manager');
  $event = $element['#event'];
  $event_meta = $event_manager
    ->getMeta($event);
  foreach ($identities as $entity_type => $identity_labels) {
    $registerable = $event_meta
      ->identitiesCanRegister($entity_type, array_keys($identity_labels));

    // Flip identity entity IDs to array keys.
    $registerable = array_flip($registerable);
    foreach (array_diff_key($identities[$entity_type], $registerable) as $id => $label) {
      $form_state
        ->setError($element, t('%name cannot register for this event.', [
        '%name' => $label,
      ]));
    }
  }
}