Files
MediaCollectorLibary/app/Controllers/Api/BaseApiController.php
Lars Behrends b728b0c72d Enhance API functionality and improve JWT authentication
- Added JWT authentication support in AuthService and JwtService.
- Implemented token generation and refresh mechanisms.
- Updated ApiAuthMiddleware to handle authentication for protected routes.
- Created ApiController and BaseApiController for standardized API responses.
- Developed MediaController for managing media items with pagination and search capabilities.
- Introduced DocsController for serving API documentation via Swagger UI.
- Added routes for API documentation and media management.
- Improved error handling and response formatting across API endpoints.
- Updated composer.json to include necessary JWT and Swagger UI dependencies.
2025-12-31 10:08:49 +01:00

63 lines
1.7 KiB
PHP

<?php
namespace App\Controllers\Api;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Controllers\Controller;
class BaseApiController extends Controller
{
protected function success(Response $response, $data = null, int $status = 200): Response
{
$responseData = ['success' => true];
if ($data !== null) {
$responseData['data'] = $data;
}
return $this->json($response, $responseData, $status);
}
protected function error(Response $response, string $message, int $status = 400, array $errors = []): Response
{
$responseData = [
'success' => false,
'error' => [
'message' => $message,
'code' => $status
]
];
if (!empty($errors)) {
$responseData['error']['details'] = $errors;
}
return $this->json($response, $responseData, $status);
}
protected function getPaginationParams(Request $request): array
{
$params = $request->getQueryParams();
$page = max(1, (int)($params['page'] ?? 1));
$perPage = min(50, max(1, (int)($params['per_page'] ?? 20)));
return [
'page' => $page,
'per_page' => $perPage,
'offset' => ($page - 1) * $perPage
];
}
protected function getAuthUser(Request $request): ?array
{
return $request->getAttribute('user');
}
protected function isAdmin(Request $request): bool
{
$user = $this->getAuthUser($request);
return $user && ($user['is_admin'] ?? false);
}
}