adlerka.top/lib/endpoint.php

76 lines
2.7 KiB
PHP

<?php
/**
* Executes an endpoint script and returns the results.
*
* This function includes an endpoint PHP file that defines a function named `endpoint` which
* is expected to accept an array parameter and return an array result.
* It simply scopes an external file into a function to prevent variable conflicts.
*
* @param string $endpoint_file The path to the endpoint PHP file.
* @return array|null Returns the result of the endpoint function if successful, or null if the
* endpoint function or file does not behave as expected.
*/
function runEndpoint(string $endpoint_file): ?array
{
$endpoint_data = $_POST;
require_once $endpoint_file;
return endpoint($endpoint_data);
}
/**
* Retrieves and processes the output of a specified endpoint.
*
* This function determines the appropriate endpoint PHP file based on the provided endpoint name,
* executes the endpoint, and returns its results as a JSON-encoded string. It handles and
* translates different return types into a JSON format and manages HTTP response codes based on
* success or failure of the endpoint execution.
*
* @param string $endpoint_name The name of the endpoint, which is used to construct the file path to the endpoint script.
* @return string A JSON-encoded string representing the result of the endpoint, including a status indicator and any relevant data or error messages.
*@global array $routerRequest Current request data that might influence the endpoint processing.
* @global array $routerConfig Global configuration that contains paths and settings.
*/
function getEndpoint(string $endpoint_name): string
{
$output = array();
$output["Status"] = "Fail";
global $routerConfig;
global $routerRequest;
if(!$endpoint_name){
$endpoint_name = $routerRequest["site_name"];
}
$endpoint_file = $routerConfig["endpoint_dir"] . $endpoint_name . ".php";
if (file_exists($endpoint_file)){
$output_tmp = runEndpoint($endpoint_file);
$output["Endpoint"] = $endpoint_name;
$type = gettype($output_tmp);
switch ($type) {
case 'array':
$output = $output_tmp;
break;
case 'string':
$output = $output_tmp;
$output['Status'] = 'Success';
break;
case 'boolean':
$output['Status'] = $output_tmp ? 'Success' : 'Fail';
break;
default:
$output['Status'] = 'Fail';
$output["Error"] = "Endpoint error";
$output["Type"] = $type;
http_response_code(500);
}
}
else{
$output["Error"] = "Not found";
http_response_code(404);
}
return json_encode($output);
}