<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\middleware;

use think\Config;
use think\Request;

class AllowCrossDomain{

	protected $header = [
		'Access-Control-Allow-Origin'      => '*',
		'Access-Control-Allow-Credentials' => 'true',
		'Access-Control-Max-Age'           => 1800,
		'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
		'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
	];

	public function __construct(Config $config){
		$this->header = array_merge($this->header, $config->get('cross', ''));
	}

	/**
	 * 允许跨域请求
	 * @access public
	 * @param Request $request
	 * @param Closure $next
	 * @param array   $header
	 * @return Response
	 */
	public function handle($request, \Closure $next, ? array $header = []){
		$response = $next($request);
		$header = !empty($header) ? array_merge($this->header, $header) : $this->header;

		if (!isset($header['Access-Control-Allow-Origin'])) {
			$origin = $request->header('origin');
			$header['Access-Control-Allow-Origin'] = $origin ? $origin : "*";
		}

		if (strtoupper($request->method()) == "OPTIONS") {
			$response->code(204);
		}

		return $response->header($header);
	}
}
