<?php
/*
 * A simple CORS middleware for Lumen framework
 *
 * lindowx
 */

namespace App\Http\Middleware;

use Closure;

class SimpleCorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $origin = $request->header('origin');
        if (
            ! empty($origin) &&
            preg_match('/^([^:]+):\/\/([^\:]+)(\:\d+)?\/?$/i', $origin, $matches)
        ) {

            //Comma separated string contains multiple origin.
            //Supports wildcard pattern
            //.env variable examples:
            //      SIMPLE_CORS_ALLOWED_ORIGINS=example.com
            //      SIMPLE_CORS_ALLOWED_ORIGINS=*.example.com
            //      SIMPLE_CORS_ALLOWED_ORIGINS=test.com,*.foor.com
            $allowedOriginsCfg = env('SIMPLE_CORS_ALLOWED_ORIGINS');
            $allowedOriginsPattern = str_replace(
                [' ',   ',',   '.',    '-',    '_',    '*', ],
                ['',    '|',   '\.',   '\-',   '\_',   '.*', ],
                $allowedOriginsCfg
            );

            $pattern = sprintf('/^(%s)$/i', $allowedOriginsPattern);
            if ( preg_match($pattern, $matches[2],$m) ) {
                return $next($request)
                    ->header('Access-Control-Allow-Origin', $origin)
                    ->header('Access-Control-Allow-Methods', '*')
                    ->header('Vary', 'origin');
            }
        }

        return $next($request);
    }
}