You are here

public function AddTeamMembersForm::validateForm in Apigee Edge 8

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

modules/apigee_edge_teams/src/Form/AddTeamMembersForm.php, line 180

Class

AddTeamMembersForm
Add team members form.

Namespace

Drupal\apigee_edge_teams\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $emails = array_map('trim', explode(',', $form_state
    ->getValue('developers', '')));
  $members = $this->teamMembershipManager
    ->getMembers($this->team
    ->id());
  $already_members = array_unique(array_intersect($emails, $members));

  // Validate existing members.
  if (count($already_members)) {
    $form_state
      ->setErrorByName('developers', $this
      ->formatPlural(count($already_members), 'The following developer is already a member of the @team: %developers.', 'The following developers are already members of the @team: %developers.', [
      '%developers' => implode(', ', $already_members),
      '@team' => mb_strtolower($this->team
        ->getEntityType()
        ->getSingularLabel()),
    ]));
  }

  // Validate pending invitations.
  $invites = array_diff($emails, $members);
  $has_invitation = [];
  foreach ($invites as $invite) {
    $pending_invitations = array_filter($this->teamInvitationStorage
      ->loadByRecipient($invite, $this->team
      ->id()), function (TeamInvitationInterface $team_invitation) {
      return $team_invitation
        ->isPending();
    });
    if (count($pending_invitations)) {
      $has_invitation[] = $invite;
    }
  }
  $has_invitation = array_unique($has_invitation);
  if (count($has_invitation)) {
    $form_state
      ->setErrorByName('developers', $this
      ->formatPlural(count($has_invitation), 'The following developer has already been invited to the @team: %developers.', 'The following developers have already been invited to the @team: %developers.', [
      '%developers' => implode(', ', $has_invitation),
      '@team' => mb_strtolower($this->team
        ->getEntityType()
        ->getSingularLabel()),
    ]));
  }
  parent::validateForm($form, $form_state);
}