Standard\Controllers\UsersController::upsertUserProcessAction PHP Method

upsertUserProcessAction() public method

    public function upsertUserProcessAction()
    {
        $id = $_POST['id'] ?? null;
        if ($id && !ctype_digit($id)) {
            $this->flasher->error('E01 Invalid user ID: ' . $id);
            $this->redirect('/users');
        }
        $user = null;
        if ($id) {
            $user = Gatekeeper::findUserById($id);
            if (!$user) {
                $this->flasher->error('E02 Invalid user ID: ' . $id);
            }
        }
        // Validation
        try {
            v::alnum('- .')->setName('First name')->check($_POST['firstName']);
            v::alnum('- .')->setName('Last name')->check($_POST['lastName']);
            v::email()->setName('Email')->check($_POST['email']);
            if (!$user) {
                v::notEmpty()->setName('Password')->check($_POST['password']);
            }
            $_POST['username'] = $_POST['email'];
            $_POST['groups'] = array_map('intval', array_filter($_POST['groups']));
        } catch (ValidationException $e) {
            $this->flasher->error($e->getMainMessage());
            echo $this->twig->render('users/upsert.twig', ['flashes' => $this->flasher->display(), 'user' => $user ?: $_POST, 'groups' => $this->gk_groups]);
            return false;
        }
        if ($user) {
            $user->firstName = $_POST['firstName'];
            $user->lastName = $_POST['lastName'];
            $user->email = $_POST['email'];
            $user->username = $_POST['email'];
            if (!empty($_POST['password'])) {
                $user->password = $_POST['password'];
            }
            $user->save();
            foreach ($user->groups as $group) {
                $user->revokeGroup($group->id);
            }
            foreach ($_POST['groups'] as $group) {
                $user->addGroup($group);
            }
            (bool) $_POST['active'] ?? false ? $user->activate() : $user->deactivate();
            $this->flasher->success('Successfully updated user.');
            $this->redirect('/users/add/' . $user->id);
        } else {
            $groups = $_POST['groups'];
            unset($_POST['groups']);
            if ($user = Gatekeeper::register($_POST)) {
                foreach ($groups as $group) {
                    $user->addGroup($group);
                }
            }
            if (Gatekeeper::getLastError()) {
                $this->flasher->error($this->site['debug'] ? Gatekeeper::getLastError() : "Could not create user!");
                echo $this->twig->render('users/upsert.twig', ['flashes' => $this->flasher->display(), 'user' => $user ?: $_POST, 'groups' => $this->gk_groups]);
                return false;
            }
            $this->flasher->success('Successfully created user.');
            $this->redirect('/users');
        }
        return true;
    }