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(array $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(array $data = []): object {
        $post = $this->GetPost();
        // validate, create, return
    }

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

    public function Delete(array $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;

GetAuthorizationToken(): string

Extracts the Bearer token from the Authorization header. Throws MagratheaApiException if missing.

$token = $this->GetAuthorizationToken();

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

Decodes the current request's Bearer token. Returns the payload object or false on failure.

$info = $this->GetTokenInfo();
if (!$info) {
    throw new MagratheaApiException("Invalid token", 401);
}

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

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

Store a response in the file cache under the given name.

public function List(): array {
    $this->Cache("products_list");
    $result = ProductControl::GetAll();
    $this->Cache("products_list", json_encode($result));
    return $result;
}

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

Clear a specific cache entry.

public function Create(array $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", 0, null, true);
        }

        // 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