PHP-Course/exam/api/Register/Register.php
2024-07-23 01:12:05 +02:00

62 lines
1.6 KiB
PHP

<?php
namespace Api\Register;
use Exception;
use Khofmann\Api\Api;
use Khofmann\ApiError\ApiError;
use Khofmann\Input\Input;
use Khofmann\Response\Response;
use Khofmann\Models\User\User;
class Register extends Api
{
public function post(): void
{
// Fetch all required inputs.
// Throw 400 error if a required one is missing.
$missing = [];
$username = Input::post("username");
$email = Input::post("email");
$password = Input::post("password");
if (empty($username)) array_push($missing, "username");
if (empty($email)) array_push($missing, "email");
if (empty($password)) array_push($missing, "password");
if (count($missing) > 0) throw ApiError::missingField($missing);
// Try and create a new user, 400 if duplicate.
try {
Response::json(User::create($username, $email, $password));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::failed("Failed to create user");
case "Duplicate":
throw ApiError::duplicate("user");
default:
throw $err;
}
}
}
public function patch(): void
{
// Fetch all required inputs.
// Throw 400 error if a required one is missing.
$code = Input::post("code");
if (empty($code)) throw ApiError::missingField(["code"]);
// Try and confirm user, 404 if user not found.
try {
Response::json(User::confirm($code));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw ApiError::notFound("user");
default:
throw $err;
}
}
}
}