100 lines
2.4 KiB
PHP
100 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Api\Users;
|
|
|
|
use Exception;
|
|
use Khofmann\Api\Api;
|
|
use Khofmann\Input\Input;
|
|
use Khofmann\Models\User\User;
|
|
use Khofmann\Response\Response;
|
|
use Khofmann\ApiError\ApiError;
|
|
use Khofmann\Request\Request;
|
|
|
|
class Users extends Api
|
|
{
|
|
public function list()
|
|
{
|
|
// Fetch and constrain all parameters.
|
|
$page = max(0, intval(Input::get("p", 0)));
|
|
$limit = constrain(0, 30, intval(Input::get("l", 10)));
|
|
|
|
// Return list of users.
|
|
Response::json(User::list($page, $limit));
|
|
}
|
|
|
|
public function get($id): void
|
|
{
|
|
// Try and get a user, 404 if not found.
|
|
try {
|
|
Response::json(User::getByID($id));
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::notFound("user");
|
|
default:
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
|
|
public function patch($id): void
|
|
{
|
|
// Fetch all inputs.
|
|
$username = Input::patch("username");
|
|
$password = Input::patch("password");
|
|
$email = Input::patch("email");
|
|
|
|
// Try and update user.
|
|
// Throw errors according to situation.
|
|
try {
|
|
Response::json(User::getByID($id)->update($username, $password, $email));
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::notFound("user");
|
|
default:
|
|
// Due to how the failed field is handled, it's ApiError is inside the models update
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
|
|
public function patchSelf(): void
|
|
{
|
|
// Fetch all inputs.
|
|
$token = Request::token();
|
|
$username = Input::patch("username");
|
|
$password = Input::patch("password");
|
|
$email = Input::patch("email");
|
|
|
|
// Try and update user.
|
|
// Throw errors according to situation.
|
|
try {
|
|
Response::json(User::getByToken($token)->update($username, $password, $email));
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::notFound("user");
|
|
default:
|
|
// Due to how the failed field is handled, it's ApiError is inside the models update
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
|
|
public function delete($id): void
|
|
{
|
|
// Try to delete user, 404 if not found.
|
|
try {
|
|
Response::json(User::getByID($id)->delete());
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::notFound("user");
|
|
default:
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
}
|