Skip to content

Instantly share code, notes, and snippets.

@designly1
Last active December 31, 2023 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designly1/c60569e91e52abc2ceb275e73a920bd8 to your computer and use it in GitHub Desktop.
Save designly1/c60569e91e52abc2ceb275e73a920bd8 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error 404</title
</head>
<body>
<p>Error 404 - Not Found
</body>
</html>
<?php
class ApiHelper
{
/**
* Send CORS headers.
*
* @return void
*/
public static function corsHeaders(): void
{
if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], ALLOWED_CORS_ORIGINS)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
}
}
/**
* Assert allowed methods.
*
* @param array $allowedMethods An array of allowed methods.
* @return void
*/
public static function assertAllowedMethods(array $allowedMethods = ['GET', 'OPTIONS']): void
{
if (!in_array($_SERVER['REQUEST_METHOD'], $allowedMethods)) {
self::methodNotAllowed();
}
}
/**
* Require POST parameters.
*
* @param array $params An array of required POST parameter keys.
* @return void
*/
public static function requirePostParameters(array $params): void
{
foreach ($params as $param) {
if (!isset($_POST[$param])) {
self::badRequest('Missing required parameter: ' . $param);
}
}
}
/**
* Apply JSON request to $_POST
*
* @return void
*/
public static function applyJsonRequest(): void
{
$data = json_decode(file_get_contents('php://input'), true);
if (is_array($data)) {
foreach ($data as $key => $value) {
$_POST[$key] = $value;
}
}
}
/**
* Send JSON response
*
* @param array $data The data to send.
* @return void
*/
public static function json(array $data): void
{
self::corsHeaders();
echo json_encode($data);
exit;
}
/**
* Send error response.
*
* @param string $message The error message.
* @return void
*/
public static function error(string $message): void
{
http_response_code(400);
self::corsHeaders();
echo json_encode([
'message' => $message,
'success' => false,
]);
exit;
}
public static function post(string $url, array $data, string $method = 'POST'): string
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
]);
$response = curl_exec($ch);
// Throw error on non 200
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
throw new Exception($response);
}
curl_close($ch);
return $response;
}
/**
* Perform a PUT request.
*
* @param string $url The URL to put to.
* @param array $data The data to put.
* @return string The response.
*/
public static function put(string $url, array $data): string
{
return self::post($url, $data, 'PUT');
}
/**
* Send a success response.
*
* @param array $data The data to send.
* @return void
*/
public static function success(array $data = []): void
{
http_response_code(200);
self::corsHeaders();
echo json_encode([
'data' => $data,
'success' => true,
'message' => null,
]);
exit;
}
/**
* Send a raw success response.
*
* @param string $data The data to send.
* @return void
*/
public static function rawSuccess($data): void
{
http_response_code(200);
self::corsHeaders();
echo $data;
exit;
}
/**
* Send a HTTP 400 Bad Request response.
*
* @param string $data The data to send.
* @return void
*/
public static function badRequest(string $message = 'Bad Request'): void
{
http_response_code(400);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 401 Unauthorized response.
*
* @param string $data The data to send.
* @return void
*/
public static function unauthorized(string $message = 'Unauthorized'): void
{
http_response_code(401);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 403 Forbidden response.
*
* @param string $data The data to send.
* @return void
*/
public static function forbidden(string $message = 'Forbidden'): void
{
http_response_code(403);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 404 Not Found response.
*
* @param string $data The data to send.
* @return void
*/
public static function notFound(string $message = 'Not Found'): void
{
http_response_code(404);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 500 Internal Server Error response.
*
* @param string $data The data to send.
* @return void
*/
public static function internalServerError(string $message = 'Internal Server Error'): void
{
http_response_code(500);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 501 Not Implemented response.
*
* @param string $data The data to send.
* @return void
*/
public static function notImplemented(string $message = 'Not Implemented'): void
{
http_response_code(501);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 502 Bad Gateway response.
*
* @param string $data The data to send.
* @return void
*/
public static function badGateway(string $message = 'Bad Gateway'): void
{
http_response_code(502);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 503 Service Unavailable response.
*
* @param string $data The data to send.
* @return void
*/
public static function serviceUnavailable(string $message = 'Service Unavailable'): void
{
http_response_code(503);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 504 Gateway Timeout response.
*
* @param string $data The data to send.
* @return void
*/
public static function gatewayTimeout(string $message = 'Gateway Timeout'): void
{
http_response_code(504);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
/**
* Send a HTTP 405 Method Not Allowed response.
*
* @param string $data The data to send.
* @return void
*/
public static function methodNotAllowed(string $message = 'Method Not Allowed'): void
{
http_response_code(405);
self::corsHeaders();
echo json_encode([
'error' => $message,
'success' => false,
]);
exit;
}
}
<?php
include (ERROR_404_HTML_FILE);
<?php
http_response_code(404);
include (ERROR_404_HTML_FILE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment