<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\middleware;

use think\Config;
use think\Request;
use think\Response;
use \Closure;

/**
 * @package app\common\middleware
 * @class AllowOrigin
 * @author xzncit 2023-08-26
 */
class AllowOrigin {

    /**
     * @var array|mixed
     */
    protected $cookieDomain;

    /**
     * @var string[]
     */
    protected $headers = [
        'Access-Control-Allow-Credentials'  => 'true',
        'Access-Control-Allow-Origin'       => '*',
        'Access-Control-Allow-Headers'      => 'Authorization, Content-Type, Client-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
        'Access-Control-Allow-Methods'      => 'GET,POST,PATCH,PUT,DELETE,OPTIONS',
        'Access-Control-Max-Age'            =>  '1728000'
    ];

    /**
     * AllowOrigin constructor.
     * @param Config $config
     */
    public function __construct(Config $config){
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next){
        $header = $this->headers;
        $origin = $request->header('origin');

        if(!empty($origin) && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))){
            $header['Access-Control-Allow-Origin'] = $origin;
        }else{
            $header['Access-Control-Allow-Origin'] = '*';
        }

        if($request->method(true) == 'OPTIONS'){
            return Response::create()->code(204)->header($header);
        }

        return $next($request)->header($header);
    }

}