Magrathea PHP 2

MagratheaApi
in package

Creates and manages a RESTful API server.

This class is responsible for routing requests, handling authorization, and returning JSON responses.

Table of Contents

Properties

$action  : string
$apiAddress  : string|null
$authClass  : MagratheaApiControl|null
$baseAuth  : string|null
$control  : string
$params  : array<string, mixed>
$returnRaw  : bool
$inst  : MagratheaApi|null
$acceptControlAllowHeaders  : array<string|int, string>
$endpoints  : array<string, array<string, mixed>>
$fallback  : callable|null

Methods

__construct()  : mixed
Constructor. Initializes the endpoint arrays for different HTTP methods.
AcceptHeaders()  : mixed
Sets the `Access-Control-Allow-Headers` CORS header.
Add()  : MagratheaApi
Adds a custom endpoint to the API.
AddAcceptHeaders()  : mixed
Adds a header to the list of accepted headers for CORS.
Allow()  : MagratheaApi
Includes CORS headers to allow requests from a specific list of origins.
AllowAll()  : MagratheaApi
Includes CORS headers to allow requests from any origin.
BaseAuthorization()  : MagratheaApi
Defines the base authorization handler.
Cache()  : mixed
Handles caching for the API response.
Crud()  : MagratheaApi
Adds a standard set of CRUD (Create, Read, Update, Delete) endpoints for a model.
Debug()  : MagratheaApi
Prints a debug view of all registered endpoints.
DisableCache()  : MagratheaApi
Sets headers to disable browser and proxy caching.
ExecuteUrl()  : mixed
Finds the matching endpoint for a given URL and method, and executes it.
Fallback()  : MagratheaApi
Sets a fallback function to be called when no route matches the request.
GetAddress()  : string|null
Gets the base address of the API.
GetEndpoints()  : array<string, array<string, array<string, mixed>>>
Gets a structured array of all registered endpoints, grouped by control class.
GetEndpointsDetail()  : array<string, array<int, array<string, mixed>>>
Gets a detailed list of all endpoints, grouped by URL.
HealthCheck()  : mixed
Creates a simple `/health-check` endpoint.
Json()  : mixed
Outputs a JSON response and terminates the script.
ReturnApiException()  : mixed
Formats and returns a MagratheaApiException as a JSON response.
ReturnError()  : mixed
Returns a generic JSON error response.
ReturnFail()  : mixed
Returns a failure JSON response.
ReturnSuccess()  : mixed
Returns a successful JSON response.
Run()  : mixed
Starts the API, processes the request, and returns the response.
SetAddress()  : MagratheaApi
Sets the base address for the API.
SetRaw()  : MagratheaApi
Configures the API to return the raw result instead of a JSON-encoded response.
Start()  : MagratheaApi
CompareRoute()  : bool
Compares a registered route pattern with the current request URL.
FindRoute()  : string|false
Finds a matching route for the given URL from the list of available API URLs.
getAuthFunction()  : string|bool|null
Determines the authorization function to use for an endpoint.
GetData()  : mixed
Calls the action on the control or the callable function for an endpoint.
getMethod()  : string
Gets the HTTP request method, handling OPTIONS requests for CORS preflight.
GetParamsFromRoute()  : array<string, string>|false
Extracts parameters from a URL based on a route pattern.
Return404()  : mixed
Returns a JSON 404 Not Found error.

Properties

$action

public string $action = "Index"

The default action to be called.

$apiAddress

public string|null $apiAddress = null

The base URL of the API.

$baseAuth

public string|null $baseAuth = null

The name of the default authorization method to be called.

$control

public string $control = "Home"

The default control to be called.

$params

public array<string, mixed> $params = array()

The parameters from the request.

$returnRaw

public bool $returnRaw = false

If true, the API will return the result instead of a JSON response.

$acceptControlAllowHeaders

private array<string|int, string> $acceptControlAllowHeaders = ["Authorization", "Content-Type"]

An array of headers to be accepted by Access-Control-Allow-Headers.

$endpoints

private array<string, array<string, mixed>> $endpoints = array()

Stores the defined API endpoints.

$fallback

private callable|null $fallback = null

A fallback function to be executed if no route is matched.

Methods

__construct()

Constructor. Initializes the endpoint arrays for different HTTP methods.

public __construct() : mixed

AcceptHeaders()

Sets the `Access-Control-Allow-Headers` CORS header.

public AcceptHeaders([array<string|int, string>|null $headers = null ]) : mixed
Parameters
$headers : array<string|int, string>|null = null

Additional headers to accept.

Add()

Adds a custom endpoint to the API.

public Add(string $method, string $url, MagratheaApiControl|null $control, string|callable $function[, string|bool $auth = false ][, string|null $description = null ]) : MagratheaApi
Parameters
$method : string

HTTP method (GET, POST, PUT, DELETE).

$url : string

The URL pattern for the endpoint.

$control : MagratheaApiControl|null

The control class that handles the request.

$function : string|callable

The method or function to be called.

$auth : string|bool = false

The authorization rule. false for public.

$description : string|null = null

A description of the endpoint for documentation.

Return values
MagratheaApi

itself for method chaining.

AddAcceptHeaders()

Adds a header to the list of accepted headers for CORS.

public AddAcceptHeaders(string|array<string|int, string> $accept) : mixed
Parameters
$accept : string|array<string|int, string>

The header(s) to add.

Allow()

Includes CORS headers to allow requests from a specific list of origins.

public Allow(array<string|int, string> $allowedOrigins) : MagratheaApi
Parameters
$allowedOrigins : array<string|int, string>

An array of allowed origin URLs.

Return values
MagratheaApi

itself for method chaining.

BaseAuthorization()

Defines the base authorization handler.

public BaseAuthorization(MagratheaApiControl $authClass, string|null $function) : MagratheaApi
Parameters
$authClass : MagratheaApiControl

The class containing authorization methods.

$function : string|null

The name of the default authorization method.

Return values
MagratheaApi

itself for method chaining.

Cache()

Handles caching for the API response.

public Cache(array<string, mixed> $data) : mixed
Parameters
$data : array<string, mixed>

The data to be cached.

Crud()

Adds a standard set of CRUD (Create, Read, Update, Delete) endpoints for a model.

public Crud(string|array<string|int, string> $url, MagratheaApiControl $control[, string|bool $auth = false ]) : MagratheaApi
Parameters
$url : string|array<string|int, string>

URL for the resource. Can be a string or an array with [singular, plural].

$control : MagratheaApiControl

The control class that handles the CRUD operations.

$auth : string|bool = false

The authorization rule for these endpoints. false for public.

Return values
MagratheaApi

itself for method chaining.

ExecuteUrl()

Finds the matching endpoint for a given URL and method, and executes it.

public ExecuteUrl(string $fullUrl[, string $method = "GET" ]) : mixed
Parameters
$fullUrl : string

The full request URL path.

$method : string = "GET"

The HTTP request method.

Return values
mixed

The result of the endpoint execution.

Fallback()

Sets a fallback function to be called when no route matches the request.

public Fallback(callable $fn) : MagratheaApi
Parameters
$fn : callable

The function to execute.

Return values
MagratheaApi

itself for method chaining.

GetAddress()

Gets the base address of the API.

public GetAddress() : string|null
Return values
string|null

api address

GetEndpoints()

Gets a structured array of all registered endpoints, grouped by control class.

public GetEndpoints() : array<string, array<string, array<string, mixed>>>
Return values
array<string, array<string, array<string, mixed>>>

A multi-dimensional array of endpoints.

GetEndpointsDetail()

Gets a detailed list of all endpoints, grouped by URL.

public GetEndpointsDetail() : array<string, array<int, array<string, mixed>>>
Return values
array<string, array<int, array<string, mixed>>>

A detailed array of endpoint configurations.

HealthCheck()

Creates a simple `/health-check` endpoint.

public HealthCheck() : mixed

Json()

Outputs a JSON response and terminates the script.

public Json(array<string|int, mixed>|object $response[, int $code = 200 ]) : mixed
Parameters
$response : array<string|int, mixed>|object

The data to be encoded as JSON.

$code : int = 200

The HTTP status code to send.

Return values
mixed

The raw response if returnRaw is true.

ReturnError()

Returns a generic JSON error response.

public ReturnError([int $code = 500 ][, string $message = "" ][, mixed|null $data = null ][, int $status = 200 ]) : mixed
Parameters
$code : int = 500

The error code.

$message : string = ""

The error message.

$data : mixed|null = null

Additional error data.

$status : int = 200

The HTTP status code.

ReturnFail()

Returns a failure JSON response.

public ReturnFail(mixed $data) : mixed
Parameters
$data : mixed

The error data or exception.

ReturnSuccess()

Returns a successful JSON response.

public ReturnSuccess(mixed $data) : mixed
Parameters
$data : mixed

The payload to include in the response.

Run()

Starts the API, processes the request, and returns the response.

public Run([bool $returnRaw = false ]) : mixed
Parameters
$returnRaw : bool = false

If true, returns the raw data instead of a JSON response.

Return values
mixed

The result of the API execution.

SetRaw()

Configures the API to return the raw result instead of a JSON-encoded response.

public SetRaw() : MagratheaApi
Return values
MagratheaApi

itself for method chaining.

Start()

public Start() : MagratheaApi
Tags
deprecated

This method is deprecated. Initialization is now handled differently. Start the server, getting base calls

Return values
MagratheaApi

itself

CompareRoute()

Compares a registered route pattern with the current request URL.

private CompareRoute(array<string|int, string> $route, array<string|int, string> $url) : bool
Parameters
$route : array<string|int, string>

The route pattern segments.

$url : array<string|int, string>

The request URL segments.

Return values
bool

True if the URL matches the route pattern.

FindRoute()

Finds a matching route for the given URL from the list of available API URLs.

private FindRoute(array<string|int, string> $url, array<string, array<string|int, mixed>>|false $apiUrls) : string|false
Parameters
$url : array<string|int, string>

The request URL segments.

$apiUrls : array<string, array<string|int, mixed>>|false

The available endpoints for the request method.

Return values
string|false

The matched route pattern or false if no match is found.

getAuthFunction()

Determines the authorization function to use for an endpoint.

private getAuthFunction(string|bool $auth) : string|bool|null
Parameters
$auth : string|bool

The auth setting for the endpoint.

Return values
string|bool|null

The name of the auth function or false if public.

GetData()

Calls the action on the control or the callable function for an endpoint.

private GetData(MagratheaApiControl|null $control, string|callable $fn[, array<string, mixed>|null $params = null ]) : mixed
Parameters
$control : MagratheaApiControl|null

The control instance.

$fn : string|callable

The function/method name or callable.

$params : array<string, mixed>|null = null

Parameters to pass to the function.

Return values
mixed

The data returned by the executed function.

getMethod()

Gets the HTTP request method, handling OPTIONS requests for CORS preflight.

private getMethod() : string
Return values
string

The HTTP method (e.g., "GET", "POST").

GetParamsFromRoute()

Extracts parameters from a URL based on a route pattern.

private GetParamsFromRoute(string $route, array<string|int, string> $url) : array<string, string>|false
Parameters
$route : string

The matched route pattern (e.g., "user/:id").

$url : array<string|int, string>

The request URL segments.

Return values
array<string, string>|false

An associative array of parameters, or false if no params.

Return404()

Returns a JSON 404 Not Found error.

private Return404() : mixed

        
On this page

Search results