/**
  * @param Invitation $invitation
  * @return EntityResultObject
  * @throws InvitationAlreadyExistsException
  * @throws UserAlreadyExistsException
  */
 public function createInvitation(Invitation $invitation)
 {
     $isEmailRegistered = $this->usersReader->isEmailRegistered($invitation->email);
     if ($isEmailRegistered === true) {
         throw new UserAlreadyExistsException();
     }
     $this->invitationsHandler->process($invitation);
     $resultObject = new EntityResultObject($invitation);
     $this->onInvitationCreation($invitation, $resultObject);
     return $resultObject;
 }
 /**
  * @param User $newUser
  * @param Invitation $invitation
  * @return User
  * @throws DuplicateUsernameException
  * @throws DuplicateEmailException
  * @throws InvalidUserInvitationEmailException
  */
 public function registerUser(User $newUser, Invitation $invitation)
 {
     if ($newUser->email !== $invitation->email) {
         throw new InvalidUserInvitationEmailException();
     }
     $this->em->beginTransaction();
     $user = $this->em->safePersist($newUser);
     if ($user === false) {
         $this->em->rollback();
         // e.g. when two users are trying to register
         // at the same time on the same Invitation
         if ($this->usersReader->isEmailRegistered($newUser->email)) {
             $this->invitationsWriter->removeInvitation($invitation);
             throw new DuplicateEmailException();
         }
         if ($this->usersReader->isUsernameRegistered($newUser->username)) {
             throw new DuplicateUsernameException();
         }
     }
     $this->invitationsWriter->removeInvitation($invitation);
     $this->em->commit();
     return $user;
 }