Add strict types and type hints across API

Apply strict_types and extensive type declarations throughout the API and models, improving type safety and error handling. Key changes: add declare(strict_types=1) to many files; convert properties, method parameters and return values to typed signatures (PDO, arrays, ints, strings, bools, nullables); switch exception handling to Throwable in index and Router; improve Router, controllers and model method signatures and nullability handling; refine file/image serving security checks and headers in ImageController; strengthen Database typing and initialization methods; return explicit types from BaseModel CRUD helpers and counting; update Media/Cast/Adult/Game/Console/Settings controllers and models to use typed methods, better validation, and clearer update/create return types. Also add AGENTS.md (agent skills index), update README with Swagger/OpenAPI usage instructions, and add /.windsurf to .gitignore. These changes aim to harden runtime correctness, make intended contracts explicit, and prepare the codebase for easier maintenance and static analysis.
This commit is contained in:
Lars Behrends
2026-04-16 16:40:31 +02:00
parent 728ca893b1
commit e38a6e1f7b
26 changed files with 545 additions and 419 deletions

View File

@@ -1,10 +1,13 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../database.php';
class ApiLogger {
private static $instance = null;
private $pdo;
private $enabled;
private static ?ApiLogger $instance = null;
private PDO $pdo;
private bool $enabled;
private function __construct() {
$this->enabled = API_LOGGING_ENABLED;
@@ -12,14 +15,14 @@ class ApiLogger {
$this->pdo = $db->getConnection();
}
public static function getInstance() {
public static function getInstance(): ApiLogger {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function logRequest($method, $path, $params = [], $body = null) {
public function logRequest(string|array $method, string|array $path, array $params = [], string|array|null $body = null): void {
if (!$this->enabled) {
return;
}
@@ -29,7 +32,7 @@ class ApiLogger {
INSERT INTO api_logs (type, method, path, params, body)
VALUES ('REQUEST', :method, :path, :params, :body)
");
$methodValue = is_array($method) ? (json_encode($method) ?: '[array]') : (string)$method;
$pathValue = is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path;
$paramsValue = is_array($params) ? (json_encode($params) ?: '[array]') : (string)$params;
@@ -37,19 +40,19 @@ class ApiLogger {
if ($body) {
$bodyValue = is_array($body) ? (json_encode($body) ?: '[array]') : (string)$body;
}
$stmt->execute([
':method' => $methodValue,
':path' => $pathValue,
':params' => $paramsValue,
':body' => $bodyValue
]);
} catch (Exception $e) {
} catch (Throwable $e) {
error_log('Failed to log request: ' . $e->getMessage());
}
}
public function logResponse($method, $path, $statusCode, $response) {
public function logResponse(string|array $method, string|array $path, int $statusCode, array $response): void {
if (!$this->enabled) {
return;
}
@@ -65,12 +68,12 @@ class ApiLogger {
':status_code' => $statusCode,
':response' => (json_encode($response) ?: '[encoding_failed]')
]);
} catch (Exception $e) {
} catch (Throwable $e) {
error_log('Failed to log response: ' . $e->getMessage());
}
}
public function logError($method, $path, $error) {
public function logError(string|array $method, string|array $path, string|array $error): void {
if (!$this->enabled) {
return;
}
@@ -85,12 +88,12 @@ class ApiLogger {
':path' => is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path,
':error' => is_array($error) ? (json_encode($error) ?: '[array]') : (string)$error
]);
} catch (Exception $e) {
} catch (Throwable $e) {
error_log('Failed to log error: ' . $e->getMessage());
}
}
public function logDebug($message) {
public function logDebug(string|array $message): void {
if (!$this->enabled) {
return;
}
@@ -103,7 +106,7 @@ class ApiLogger {
$stmt->execute([
':message' => is_array($message) ? (json_encode($message) ?: '[array]') : (string)$message
]);
} catch (Exception $e) {
} catch (Throwable $e) {
error_log('Failed to log debug: ' . $e->getMessage());
}
}

View File

@@ -1,15 +1,17 @@
<?php
declare(strict_types=1);
class DocumentationService {
private $controllersPath;
private $modelsPath;
public function __construct($controllersPath = __DIR__ . '/../controllers/', $modelsPath = __DIR__ . '/../models/') {
private string $controllersPath;
private string $modelsPath;
public function __construct(string $controllersPath = __DIR__ . '/../controllers/', string $modelsPath = __DIR__ . '/../models/') {
$this->controllersPath = $controllersPath;
$this->modelsPath = $modelsPath;
}
public function generateDocumentation() {
public function generateDocumentation(): array {
$docs = [
'title' => 'Media API Documentation',
'version' => '1.0.0',
@@ -27,7 +29,7 @@ class DocumentationService {
return $docs;
}
private function scanControllers() {
private function scanControllers(): array {
$endpoints = [];
$controllerFiles = glob($this->controllersPath . '*Controller.php');
@@ -56,7 +58,7 @@ class DocumentationService {
return $endpoints;
}
private function parseMethodDoc($docComment, $methodName, $className) {
private function parseMethodDoc(?string $docComment, string $methodName, string $className): ?array {
if (!$docComment) {
return null;
}
@@ -106,7 +108,7 @@ class DocumentationService {
return $info;
}
private function inferHttpMethods($methodName) {
private function inferHttpMethods(string $methodName): array {
$methods = [];
if (strpos($methodName, 'get') === 0) {
@@ -129,7 +131,7 @@ class DocumentationService {
return $methods;
}
private function inferPath($className, $methodName) {
private function inferPath(string $className, string $methodName): string {
$resource = strtolower(str_replace('Controller', '', $className));
$path = "/{$resource}";
@@ -156,7 +158,7 @@ class DocumentationService {
return $path;
}
private function scanModels() {
private function scanModels(): array {
$models = [];
$modelFiles = glob($this->modelsPath . '*.php');

View File

@@ -1,27 +1,29 @@
<?php
declare(strict_types=1);
class ImageHandler {
private $uploadDir;
private $baseUrl;
public function __construct($uploadDir = null, $baseUrl = null) {
private string $uploadDir;
private string $baseUrl;
public function __construct(?string $uploadDir = null, ?string $baseUrl = null) {
$this->uploadDir = $uploadDir ?? __DIR__ . '/../public/images/';
$this->baseUrl = $baseUrl ?? '/images/';
// Ensure upload directory exists
if (!file_exists($this->uploadDir)) {
mkdir($this->uploadDir, 0755, true);
}
}
/**
* Process base64 image data and save to file
*
*
* @param string $base64Data Base64 encoded image data
* @param string $prefix Prefix for filename (e.g., 'poster', 'banner')
* @return string|null Relative path to saved image, or null if invalid
*/
public function saveBase64Image($base64Data, $prefix = 'image') {
public function saveBase64Image(string $base64Data, string $prefix = 'image'): ?string {
error_log("ImageHandler: Starting to process base64 image, length: " . strlen($base64Data));
if (empty($base64Data)) {
@@ -119,7 +121,7 @@ class ImageHandler {
/**
* Detect image format from base64 string
*/
private function detectImageFormat($base64String) {
private function detectImageFormat(string $base64String): ?string {
// Decode first few bytes to check magic numbers
$data = base64_decode(substr($base64String, 0, 100));
@@ -140,7 +142,7 @@ class ImageHandler {
/**
* Validate that data is a valid image
*/
private function isValidImage($data) {
private function isValidImage(string $data): bool {
try {
$image = imagecreatefromstring($data);
if ($image !== false) {
@@ -156,14 +158,14 @@ class ImageHandler {
/**
* Generate unique filename
*/
private function generateUniqueFilename($prefix, $extension) {
private function generateUniqueFilename(string $prefix, string $extension): string {
return $prefix . '_' . uniqid() . '_' . time() . '.' . $extension;
}
/**
* Delete an image file
*/
public function deleteImage($imagePath) {
public function deleteImage(?string $imagePath): bool {
if (empty($imagePath)) {
return false;
}