diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-15 22:10:15 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-15 22:10:15 +0300 |
| commit | 7d5e7b0f95992650189b73c6160264db6b658bde (patch) | |
| tree | b5e4229ed2119bcfc0b59cf3f634fd8fa503cf0c /classes | |
| parent | a15fe2d871772c78cacce00530211c391d52508e (diff) | |
| download | the-epube-7d5e7b0f95992650189b73c6160264db6b658bde.tar.gz the-epube-7d5e7b0f95992650189b73c6160264db6b658bde.tar.xz | |
import request with split methods and generate some tests
Diffstat (limited to 'classes')
| -rw-r--r-- | classes/CsrfMiddleware.php | 4 | ||||
| -rw-r--r-- | classes/Handler/CoverHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/DefineHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/DownloadHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/LastreadHandler.php | 10 | ||||
| -rw-r--r-- | classes/Handler/ListHandler.php | 10 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 6 | ||||
| -rw-r--r-- | classes/Handler/PaginationHandler.php | 6 | ||||
| -rw-r--r-- | classes/Handler/TogglefavHandler.php | 2 | ||||
| -rw-r--r-- | classes/Request.php | 392 |
10 files changed, 376 insertions, 60 deletions
diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php index 0a03925..c9374b0 100644 --- a/classes/CsrfMiddleware.php +++ b/classes/CsrfMiddleware.php @@ -13,9 +13,9 @@ class CsrfMiddleware implements MiddlewareInterface return $next($request); } - $op = $request->getAttribute('op'); + $op = $request->getString('op'); - $csrfToken = $request->getAttribute('csrf_token', ''); + $csrfToken = $request->getString('csrf_token', ''); if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) { $response = (new Response()) diff --git a/classes/Handler/CoverHandler.php b/classes/Handler/CoverHandler.php index 4e95e54..cd26308 100644 --- a/classes/Handler/CoverHandler.php +++ b/classes/Handler/CoverHandler.php @@ -13,7 +13,7 @@ class CoverHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $id = (int) $request->getAttribute('id'); + $id = $request->getInt('id'); $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?"); $sth->execute([$id]); diff --git a/classes/Handler/DefineHandler.php b/classes/Handler/DefineHandler.php index 60d5b11..7906adc 100644 --- a/classes/Handler/DefineHandler.php +++ b/classes/Handler/DefineHandler.php @@ -32,7 +32,7 @@ class DefineHandler implements RequestHandlerInterface, AuthRequired return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]])); } - $word = strip_tags(str_replace("", "", $request->getAttribute('word'))); + $word = strip_tags(str_replace("", "", $request->getString('word'))); $origWord = $word; $result = []; diff --git a/classes/Handler/DownloadHandler.php b/classes/Handler/DownloadHandler.php index 330c04f..da50c90 100644 --- a/classes/Handler/DownloadHandler.php +++ b/classes/Handler/DownloadHandler.php @@ -13,7 +13,7 @@ class DownloadHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $bookid = (int) $request->getAttribute('id'); + $bookid = $request->getInt('id'); $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); $sth = $caldb->prepare("SELECT path, name, format FROM data LEFT JOIN books ON (data.book = books.id) WHERE data.id = ?"); $sth->execute([$bookid]); diff --git a/classes/Handler/LastreadHandler.php b/classes/Handler/LastreadHandler.php index ab177ed..638db25 100644 --- a/classes/Handler/LastreadHandler.php +++ b/classes/Handler/LastreadHandler.php @@ -68,16 +68,16 @@ class LastreadHandler implements RequestHandlerInterface, AuthRequired public function handle(Request $request): Response { - $subOp = $request->getAttribute('op', ''); - $bookid = (int) $request->getAttribute('id'); + $subOp = $request->getString('op', ''); + $bookid = $request->getInt('id'); return match ($subOp) { 'getlastread' => $this->handleGet($bookid), 'storelastread' => $this->handleStore( $bookid, - (int) $request->getAttribute('page'), - (string) $request->getAttribute('cfi', ''), - (int) $request->getAttribute('timestamp'), + $request->getInt('page'), + $request->getString('cfi', ''), + $request->getInt('timestamp'), ), default => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])), }; diff --git a/classes/Handler/ListHandler.php b/classes/Handler/ListHandler.php index 6628cee..e8a5916 100644 --- a/classes/Handler/ListHandler.php +++ b/classes/Handler/ListHandler.php @@ -14,16 +14,16 @@ class ListHandler implements RequestHandlerInterface, AuthRequired public function handle(Request $request): Response { $owner = $_SESSION["owner"] ?? ""; - $mode = $request->getAttribute('mode', ''); - $query = $request->getAttribute('query', ''); - $limit = (int) $request->getAttribute('limit', 60); - $offset = (int) $request->getAttribute('offset', 0); + $mode = $request->getString('mode', ''); + $query = $request->getString('query', ''); + $limit = $request->getInt('limit', 60); + $offset = $request->getInt('offset', 0); $ldb = \Db::pdo(); $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); $ids = array_filter( - explode(",", $request->getAttribute('ids', '')), 'intval'); + explode(",", $request->getString('ids', '')), 'intval'); if ($mode == "favorites") { diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php index f8a2b41..7fb1449 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -107,7 +107,7 @@ class LoginHandler implements RequestHandlerInterface public function handle(Request $request): Response { - $op = $request->getAttribute('op', ''); + $op = $request->getString('op', ''); // Redirect to OIDC provider if ($op === "perform-oidc-login") { @@ -150,8 +150,8 @@ class LoginHandler implements RequestHandlerInterface // Local username/password login if ($op === "perform-login") { - $username = trim(mb_strtolower($request->getAttribute('user', ''))); - $password = $request->getAttribute('password', ''); + $username = trim(mb_strtolower($request->getString('user', ''))); + $password = $request->getString('password', ''); if (!$username || !$password) { return (new Response()) diff --git a/classes/Handler/PaginationHandler.php b/classes/Handler/PaginationHandler.php index a027c58..3c0555b 100644 --- a/classes/Handler/PaginationHandler.php +++ b/classes/Handler/PaginationHandler.php @@ -67,12 +67,12 @@ class PaginationHandler implements RequestHandlerInterface, AuthRequired public function handle(Request $request): Response { - $subOp = $request->getAttribute('op', ''); - $bookid = (int) $request->getAttribute('id'); + $subOp = $request->getString('op', ''); + $bookid = $request->getInt('id'); return match ($subOp) { 'getpagination' => $this->handleGet($bookid), - 'storepagination' => $this->handleStore($bookid, $request->getAttribute('payload')), + 'storepagination' => $this->handleStore($bookid, $request->getString('payload')), 'deletepagination' => $this->handleDelete($bookid), default => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])), }; diff --git a/classes/Handler/TogglefavHandler.php b/classes/Handler/TogglefavHandler.php index 3b203ad..d6a3913 100644 --- a/classes/Handler/TogglefavHandler.php +++ b/classes/Handler/TogglefavHandler.php @@ -12,7 +12,7 @@ class TogglefavHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $bookid = (int) $request->getAttribute('id'); + $bookid = $request->getInt('id'); $owner = $_SESSION["owner"] ?? ""; $fav = ORM::for_table('epube_favorites') diff --git a/classes/Request.php b/classes/Request.php index b3d2b62..3a8e696 100644 --- a/classes/Request.php +++ b/classes/Request.php @@ -1,57 +1,373 @@ <?php +/** + * Typed parameter extraction wrapper around PHP superglobals. + * + * Provides clean, type-safe access to request parameters, replacing the + * repetitive clean($_REQUEST['key'] ?? default) pattern throughout handlers. + * + * Usage: + * $request = new Request(); + * $id = $request->getInt('id', 0); + * $name = $request->getString('name', ''); + * $flag = $request->getBool('flag', false); + * $ids = $request->getArray('ids', []); + * + * Can also extract from specific superglobals: + * $request->fromPost()->getString('login'); + * $request->fromGet()->getInt('limit', 20); + */ +class Request { -class Request -{ - /** @var array<string, mixed> */ - private array $serverParams; - /** @var array<string, mixed> */ - private array $queryParams; - /** @var array<string, mixed> */ - private array $bodyParams; - /** @var array<string, mixed> */ - private array $cookies; + public const SOURCE_REQUEST = 'request'; + public const SOURCE_GET = 'get'; + public const SOURCE_POST = 'post'; + public const SOURCE_BODY = 'body'; - public function __construct() - { - $this->serverParams = $_SERVER; - $this->queryParams = $_GET; - $this->bodyParams = $_POST; - $this->cookies = $_COOKIE; + /** @var array<int|string, mixed>|null */ + private ?array $data = null; + + /** @var array<int|string, mixed>|null */ + private ?array $body = null; + + /** @var array<int|string, mixed> */ + private array $attributes = []; + + /** @var self::SOURCE_* */ + private string $source = self::SOURCE_REQUEST; + + /** + * @param array<int|string, mixed>|null $data Optional explicit data source (e.g. from constructor arg) + */ + public function __construct(?array $data = null) { + $this->data = $data; + } + + /** + * Extract from the given superglobal. + * + * @param self::SOURCE_* $source + * @return $this + */ + public function from(string $source): self { + $this->source = $source; + return $this; + } + + /** + * Extract from $_POST. + * @return $this + */ + public function fromPost(): self { + return $this->from(self::SOURCE_POST); + } + + /** + * Extract from $_GET. + * @return $this + */ + public function fromGet(): self { + return $this->from(self::SOURCE_GET); + } + + /** + * Extract from $_REQUEST (default). + * @return $this + */ + public function fromRequest(): self { + return $this->from(self::SOURCE_REQUEST); } - /** @return array<string, mixed> */ - public function getServerParams(): array - { - return $this->serverParams; + /** + * Extract from the raw request body (php://input). + * + * Inspects Content-Type to determine parsing strategy: + * - application/json / text/json → JSON decode + * - application/x-www-form-urlencoded → parse_str (like $_POST) + * - anything else / missing → empty array + * + * If JSON decoding fails, an empty array is returned so downstream + * getters fall back to defaults. + * + * Useful for PATCH/PUT requests where $_POST is not populated. + * + * @return $this + */ + public function fromBody(): self { + if ($this->body !== null) { + return $this; + } + + $raw = file_get_contents('php://input'); + if ($raw === '') { + $this->body = []; + return $this; + } + + // Determine content type, stripping charset etc. + $contentType = strtolower(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0]); + + if (in_array($contentType, ['application/json', 'text/json'], true)) { + $decoded = json_decode($raw, true); + $this->body = is_array($decoded) ? $decoded : []; + } elseif ($contentType === 'application/x-www-form-urlencoded') { + parse_str($raw, $parsed); + $this->body = $parsed; + } else { + $this->body = []; + } + + return $this->from(self::SOURCE_BODY); + } + + /** + * Get a sanitized string value. + * + * @param string $key + * @param string $default + * @return string + */ + public function getString(string $key, string $default = ''): string { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return clean((string)$value); } - /** @return array<string, mixed> */ - public function getQueryParams(): array - { - return $this->queryParams; + /** + * Get a sanitized integer value. + * + * @param string $key + * @param int $default + * @return int + */ + public function getInt(string $key, int $default = 0): int { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return (int) clean((string)$value); } - /** @return array<string, mixed> */ - public function getParsedBody(): array - { - return array_merge($this->queryParams, $this->bodyParams); + /** + * Get a sanitized float value. + * + * @param string $key + * @param float $default + * @return float + */ + public function getFloat(string $key, float $default = 0.0): float { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return (float) clean((string)$value); } - /** @return array<string, mixed> */ - public function getCookieParams(): array - { - return $this->cookies; + /** + * Get a sanitized boolean value. + * + * Treats the following as true: "1", "true", "t", "on", non-zero integers, + * non-empty strings. All other values are treated as false. + * + * @param string $key + * @param bool $default + * @return bool + */ + public function getBool(string $key, bool $default = false): bool { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return self::_to_bool($value); } - public function getAttribute(string $name, mixed $default = null): mixed - { - return $this->getParsedBody()[$name] ?? $default; + /** + * Get a sanitized array value. + * + * If the value is a comma-separated string, it will be split into an array. + * Each element is trimmed and HTML tags are stripped. + * + * @param string $key + * @param array<int|string, mixed> $default + * @return array<int|string, mixed> + */ + public function getArray(string $key, array $default = []): array { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + + if (is_array($value)) { + return clean($value); + } + + // Handle comma-separated string values + $cleaned = clean((string)$value); + if ($cleaned === '') { + return []; + } + + return array_map('trim', explode(',', $cleaned)); } - public function withAttribute(string $name, mixed $value): self - { + /** + * Get the raw (unsanitized) value. + * + * @param string $key + * @return mixed|null + */ + public function getRaw(string $key): mixed { + return match ($this->source) { + self::SOURCE_POST => $_POST[$key] ?? null, + self::SOURCE_GET => $_GET[$key] ?? null, + self::SOURCE_BODY => $this->body[$key] ?? null, + default => $this->data !== null ? ($this->data[$key] ?? null) : ($_REQUEST[$key] ?? null), + }; + } + + /** + * Check if a key exists in the current source. + * + * @param string $key + * @return bool + */ + public function has(string $key): bool { + return match ($this->source) { + self::SOURCE_POST => array_key_exists($key, $_POST), + self::SOURCE_GET => array_key_exists($key, $_GET), + self::SOURCE_BODY => array_key_exists($key, $this->body), + default => $this->data !== null + ? array_key_exists($key, $this->data) + : array_key_exists($key, $_REQUEST), + }; + } + + /** + * Get all parameters from the current source. + * + * @return array<int|string, mixed> + */ + public function all(): array { + return match ($this->source) { + self::SOURCE_POST => $_POST, + self::SOURCE_GET => $_GET, + self::SOURCE_BODY => $this->body ?? [], + default => $this->data !== null ? $this->data : $_REQUEST, + }; + } + + /** + * Get all query parameters (\$_GET). + * + * @return array<int|string, mixed> + */ + public function getQueryParams(): array { + return $_GET; + } + + /** + * Get all server parameters (\$_SERVER). + * + * @return array<int|string, mixed> + */ + public function getServerParams(): array { + return $_SERVER; + } + + /** + * Get all cookie parameters (\$_COOKIE). + * + * @return array<int|string, mixed> + */ + public function getCookieParams(): array { + return $_COOKIE; + } + + /** + * Get a merged body from \$_GET and \$_POST, with \$_POST values + * overriding \$_GET on key collision. + * + * @return array<int|string, mixed> + */ + public function getParsedBody(): array { + return array_merge($_GET, $_POST); + } + + /** + * Get an attribute or request parameter by key. + * + * Looks first in attributes set via withAttribute(), then in the + * parsed body (\$_GET + \$_POST merged). + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function getAttribute(string $key, mixed $default = null): mixed { + // Check attributes first + if (array_key_exists($key, $this->attributes)) { + return $this->attributes[$key]; + } + + // Fall back to parsed body + $body = $this->getParsedBody(); + return $body[$key] ?? $default; + } + + /** + * Return a clone of this request with a new attribute added. + * + * @param string $key + * @param mixed $value + * @return self + */ + public function withAttribute(string $key, mixed $value): self { $clone = clone $this; - $clone->bodyParams[$name] = $value; + $clone->attributes[$key] = $value; return $clone; } + + /** + * Get a subset of parameters by key names. + * + * @param array<int, string> $keys + * @return array<int|string, mixed> + */ + public function only(array $keys): array { + $result = []; + foreach ($keys as $key) { + $result[$key] = $this->getRaw($key); + } + return $result; + } + + /** + * Convert a value to boolean using the same logic as Handler::_param_to_bool(). + * + * @param mixed $value + * @return bool + */ + public static function _to_bool(mixed $value): bool { + $value = clean($value); + + if (is_bool($value)) { + return $value; + } + + if (is_int($value)) { + return $value !== 0; + } + + if (is_float($value)) { + return $value != 0.0; + } + + if (is_string($value)) { + $lower = strtolower($value); + return in_array($lower, ['1', 'true', 't', 'on'], true); + } + + return (bool) $value; + } } |
