<?php
declare (strict_types=1);

namespace app\api\middleware;

use app\Request;
use Closure;

/**
 * API跨域中间件
 */
class CorsMiddleware
{
    protected array $allowedOrigins = [
        '*',
    ];

    public function handle(Request $request, Closure $next)
    {
        $origin = $request->header('Origin', '');
        $allowedOrigin = $this->isOriginAllowed($origin) ? $origin : '';

        if ($allowedOrigin) {
            header('Access-Control-Allow-Origin: ' . $allowedOrigin);
            header('Access-Control-Allow-Credentials: true');
        }

        header("Access-Control-Allow-Headers: Authorization, Token, Content-Type, X-Requested-With");
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Max-Age: 1728000');

        if ($request->isOptions()) {
            return response();
        }

        return $next($request);
    }

    protected function isOriginAllowed(string $origin): bool
    {
        // 允许通配符
        if (in_array('*', $this->allowedOrigins)) {
            return true;
        }

        if (empty($origin)) {
            return false;
        }
        return in_array($origin, $this->allowedOrigins);
    }
}
