connection->transaction(function () use ($server, $email, $permissions) { try { $user = $this->userRepository->findFirstWhere([['email', '=', $email]]); if ($server->owner_id === $user->id) { throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner')); } $subuserCount = $this->subuserRepository->findCountWhere([['user_id', '=', $user->id], ['server_id', '=', $server->id]]); if ($subuserCount !== 0) { throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists')); } } catch (RecordNotFoundException) { // Just cap the username generated at 64 characters at most and then append a random string // to the end to make it "unique"... $username = substr(preg_replace('/([^\w\.-]+)/', '', strtok($email, '@')), 0, 64) . Str::random(3); $user = $this->userCreationService->handle([ 'email' => $email, 'username' => $username, 'root_admin' => false, ]); } return $this->subuserRepository->create([ 'user_id' => $user->id, 'server_id' => $server->id, 'permissions' => array_unique($permissions), ]); }); } }