Files
appraisal_center_api/app/middleware/Cors.php
2026-04-16 11:17:18 +08:00

47 lines
1.4 KiB
PHP

<?php
namespace app\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class Cors implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$origin = (string)$request->header('origin', '');
$allow = trim((string)(getenv('CORS_ALLOW_ORIGINS') ?: '*'));
$allowOrigin = '';
if ($allow === '*') {
$allowOrigin = '*';
} else {
$allowList = array_values(array_filter(array_map('trim', explode(',', $allow))));
if ($origin !== '' && in_array($origin, $allowList, true)) {
$allowOrigin = $origin;
}
}
$headers = [
'Access-Control-Allow-Methods' => 'GET,POST,PUT,PATCH,DELETE,OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With',
'Access-Control-Max-Age' => '86400',
];
if ($allowOrigin !== '') {
$headers['Access-Control-Allow-Origin'] = $allowOrigin;
if ($allowOrigin !== '*') {
$headers['Access-Control-Allow-Credentials'] = 'true';
}
}
if (strtoupper($request->method()) === 'OPTIONS') {
return response('', 204)->withHeaders($headers);
}
$response = $handler($request);
return $response->withHeaders($headers);
}
}