repository = $repository; $this->createUserInvitation = $createUserInvitation; } /** * @param Request $request * @return JsonResponse * @throws InternalServerErrorException */ public function execute(Request $request) { try { // the email doesn't exist in the database, so create the user $object = new UserInvitationObject($request->get('role_id'), $request->get('email')); // ensure that there is not already an invitation for the email $existingInvitations = $this->repository->where('email', $object->getInviteeEmail())->get(); if ($existingInvitations->count() !== 0) { throw new ResourceConflictException("An existing invitation already exists for the email {$object->getInviteeEmail()}"); } $invitation = $this->createUserInvitation->execute($object); // dispatch event for user invited event(new UserInvited($invitation)); return new JsonResponse(null, HttpStatus::RESOURCE_CREATED); } catch (ResourceConflictException $exception) { throw new InternalServerErrorException("Failed to send user invitation because {$exception->getMessage()}"); } } }