MagratheaPHP2
Up to date Narrative last written —; no source changes since. Method signatures below are reflected live.

MagratheaApiControl — API Controller Base

File: src/MagratheaApiControl.php Namespace: Magrathea2

Base class for all API controllers. Provides HTTP request parsing, JWT authentication helpers, CRUD stubs, and caching utilities.


Properties

PropertyTypeDescription
$model?stringAssociated model class name
$service?objectOptional service/helper object
$userInfo?objectDecoded JWT payload after token validation
$jwtEncodeTypestringJWT algorithm (default: "HS256")

Defining a Controller

<?php
namespace App\Api;

use Magrathea2\MagratheaApiControl;
use Magrathea2\Exceptions\MagratheaApiException;
use App\Controls\ProductControl;

class ProductApiControl extends MagratheaApiControl {

    public function List(): array {
        return ProductControl::GetAll();
    }

    public function Read($params = []): object|array {
        $id = $params["id"] ?? null;
        $product = ProductControl::GetRowWhere(["id" => $id]);
        if (!$product) throw new MagratheaApiException("Product not found", 404);
        return $product->ToJson();
    }

    public function Create($data = []): object {
        $post = $this->GetPost();
        // validate, create, return
    }

    public function Update($params): object {
        $put = $this->GetPut();
        // find, update, return
    }

    public function Delete($params = []): bool {
        $id = $params["id"] ?? null;
        $product = ProductControl::GetRowWhere(["id" => $id]);
        if (!$product) throw new MagratheaApiException("Not found", 404);
        return $product->Delete();
    }
}

HTTP Request Methods

GetAllHeaders(): array<string, string>

Returns all HTTP request headers as an associative array.

$headers = $this->GetAllHeaders();
echo $headers["Content-Type"];

GetPost(): ?array

Returns the decoded POST body. Handles both application/json and application/x-www-form-urlencoded.

$data = $this->GetPost();
$name  = $data["name"]  ?? "";
$email = $data["email"] ?? "";

GetPut(): ?array

Returns the decoded PUT (or PATCH) request body (reads from php://input).

$data = $this->GetPut();
$newPrice = $data["price"] ?? null;

GetPatch(): ?array

Alias of GetPut() — returns the decoded PATCH (or PUT) request body.

$data = $this->GetPatch();

GetPhpInput(): mixed

Returns the raw body of the current request (any method).

$raw = $this->GetPhpInput();

JWT Authentication Methods

GetSecret(): string

Returns the JWT secret from the application config. Override this to use a custom secret.

// In your AuthControl:
public function GetSecret(): string {
    return Config::Instance()->Get("jwt_secret");
}

jwtEncode(mixed $payload): string

Encodes a payload into a JWT token string.

$token = $this->jwtEncode([
    "user_id" => 42,
    "role"    => "admin",
    "exp"     => time() + 3600,
]);

jwtDecode(string $token): object

Decodes a JWT token and returns the payload as an object.

$payload = $this->jwtDecode($token);
echo $payload->user_id;

Decode failures from the underlying firebase/php-jwt library are translated into MagratheaApiException, not left to propagate as raw library exceptions:

try {
    $payload = $this->jwtDecode($token);
} catch (MagratheaApiException $ex) {
    if ($ex->getCode() === 4010) {
        $expiredAt = $ex->GetData()["expiredAt"] ?? null; // unix timestamp
    }
    throw $ex; // or handle inline
}

GetAuthorizationToken(): string

Extracts the Bearer token from the Authorization header. Throws MagratheaApiException if missing (code 400, HTTP 401 via SetStatus(401); before 2.4.0 the status was ignored and the response was HTTP 400).

$token = $this->GetAuthorizationToken();

GetTokenInfo(string|false $token = false): object|false

Decodes the current request's Bearer token. Returns false only when no token was found at all (no Authorization header, no matching cookie). If a token was found but fails to decode (expired, bad signature, malformed), it throws MagratheaApiException — via jwtDecode(), see above — rather than returning false.

$info = $this->GetTokenInfo();
if (!$info) {
    throw new MagratheaApiException("Invalid token", 401); // no token was present at all
}

GetUserInfo(): ?object

Returns the decoded user payload set during authorization.

$user = $this->GetUserInfo();
echo $user->user_id;

GetUserId(): int|null

Returns the user_id from the decoded token, or null if not set.

$userId = $this->GetUserId();

CRUD Stub Methods

These are meant to be overridden in subclasses. By default they throw Exception.

MethodHTTP MethodRoute
List(): arrayGET/resource
Read($params): object|arrayGET/resource/{id}
Create($data): objectPOST/resource
Update(array $params): objectPUT/resource/{id}
Delete($params): boolDELETE/resource/{id}

Caching Methods

See MagratheaCache for how the cache works.

Cache(string $name, string|null $data = null): void

Call it at the start of an action. On a cache hit it outputs the cached response and ends the script; on a miss it returns, and the action's successful response is saved under that key. $data is an optional key suffix (an id, a page number), not the response: the key becomes "{$name}-{$data}".

In DEV (IsDev()) it also logs adding cache for [name/data] from (<uri> -><action>) to the Logger; other environments don't log (before 2.4.0 it logged on every call, everywhere).

public function List(): array {
    $this->Cache("products_list");          // hit: served from disk, the code below never runs
    return array_map(fn($p) => $p->ToArray(), ProductControl::GetAll());
}

public function View(array $params = []): array {
    $this->Cache("product", $params["id"]); // one file per product: product-<id>.json
    return (new Product($params["id"]))->ToArray();
}

CacheClear(string $name, string|null $data = null): void

Clear a specific cache entry.

public function Create($data = []): object {
    // ... create product ...
    $this->CacheClear("products_list");
    return $product->ToJson();
}

CacheClearPattern(string $pattern): void

Clear all cache entries matching a pattern.

$this->CacheClearPattern("products_*");

Raw Output

Raw(string $content): void

Output raw (non-JSON) content and exit. Useful for file downloads, CSV exports, etc.

public function ExportCsv(): void {
    header("Content-Type: text/csv");
    $this->Raw("id,name,price\n1,Widget,9.99\n");
}

Complete Example: User Authentication API

<?php
namespace App\Api;

use Magrathea2\MagratheaApiControl;
use Magrathea2\Exceptions\MagratheaApiException;
use App\Controls\UserControl;

class AuthApiControl extends MagratheaApiControl {

    // Called for every protected route as base authorization
    public function ValidateToken(): bool {
        $token = $this->GetAuthorizationToken();
        $info  = $this->GetTokenInfo($token);

        if (!$info || !isset($info->user_id)) {
            throw new MagratheaApiException("Unauthorized", 401); // code 0 would be HTTP 500
        }

        // Store for later use in other methods
        $this->userInfo = $info;
        return true;
    }

    // POST /auth/login
    public function Login(): array {
        $post  = $this->GetPost();
        $email = $post["email"] ?? "";
        $pass  = $post["password"] ?? "";

        $user = UserControl::GetRowWhere(["email" => $email]);

        if (!$user || !password_verify($pass, $user->password_hash)) {
            throw new MagratheaApiException("Invalid credentials", 401);
        }

        $token = $this->jwtEncode([
            "user_id" => $user->id,
            "email"   => $user->email,
            "exp"     => time() + 86400, // 24 hours
        ]);

        return ["token" => $token, "user" => $user->ToJson()];
    }

    // GET /auth/me
    public function Me(): array {
        $userId = $this->GetUserId();
        $user   = UserControl::GetRowWhere(["id" => $userId]);
        return $user->ToJson();
    }
}
// In index.php:
$api->Add("POST", "/auth/login", new AuthApiControl(), "Login");
$api->Add("GET",  "/auth/me",    new AuthApiControl(), "Me", true);

Notes

Class Reference — MagratheaApiControl

Magrathea2\MagratheaApiControl /home/platypusweb/platypusweb.com.br/site/magratheaphp2/src/MagratheaApiControl.php

Base Control for API endpoints. Provides basic CRUD functionalities and helper methods for handling API requests, such as authentication, data retrieval from requests, and caching.

Cache($name, $data = null)

Caches the current request's response.

ParamTypeDefault
$name mixed required
$data mixed null
CacheClear($name, $data = null)

Clears a specific cache entry.

ParamTypeDefault
$name mixed required
$data mixed null
CacheClearPattern($pattern)

Clears cache entries matching a pattern.

ParamTypeDefault
$pattern mixed required
Create($data = false)

Creates a new item.

ParamTypeDefault
$data mixed false
Delete($params = false)

Deletes an item by its ID.

ParamTypeDefault
$params mixed false
GetAllHeaders()

Gets all HTTP headers from the request.

GetAuthorizationToken()

Gets the authorization token from the 'Authorization' header. It supports 'Basic' and 'Bearer' token types.

GetPhpInput()

Reads and parses the raw input stream (php://input).

GetPost()

Gets data from a POST request.

GetPut()

Gets data from a PUT request.

GetSecret(): string

Gets the secret key for JWT encoding/decoding from config.

GetTokenInfo($token = false)

Get token data

ParamTypeDefault
$token mixed false
GetUserId(): ?int
GetUserInfo()
List()

Lists all items using the associated service.

Raw($content)

Outputs raw text content and terminates the script.

ParamTypeDefault
$content mixed required
Read($params = false)

Reads a single item by its ID, or lists all items if no ID is provided.

ParamTypeDefault
$params mixed false
Update($params)

Updates an existing item.

ParamTypeDefault
$params mixed required
getAuthorizationHeader()

Gets the Authorization header from various server sources.

getTokenByType($type): ?string

get access token from header

ParamTypeDefault
$type mixed required
jwtDecode($token)

Decodes a JWT token.

ParamTypeDefault
$token mixed required
jwtEncode($payload)

Encodes a payload into a JWT token.

ParamTypeDefault
$payload mixed required

Examples