connection->transaction(function () use ($server, $email, $permissions) { $user = User::query()->where('email', $email)->first(); if (!$user) { // Just cap the username generated at 64 characters at most and then append a random string // to the end to make it "unique"... [$beforeDomain] = explode('@', $email, 1); $username = substr(preg_replace('/([^\w.-]+)/', '', $beforeDomain), 0, 64) . Str::random(3); $user = $this->userCreationService->handle([ 'email' => $email, 'username' => $username, 'root_admin' => false, ]); } if ($server->owner_id === $user->id) { throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner')); } $subuserCount = $server->subusers()->where('user_id', $user->id)->count(); if ($subuserCount !== 0) { throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists')); } $cleanedPermissions = collect($permissions) ->unique() ->filter(fn ($permission) => $permission === Permission::ACTION_WEBSOCKET_CONNECT || auth()->user()->can($permission, $server)) ->sort() ->values() ->all(); $subuser = Subuser::query()->create([ 'user_id' => $user->id, 'server_id' => $server->id, 'permissions' => $cleanedPermissions, ]); event(new SubUserAdded($subuser)); return $subuser; }); } }