<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Middleware\HandleCors as BaseHandleCors;
use Illuminate\Http\Request;

class ConditionalCors
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $paths = config('cors.paths', null);

        // If paths are empty the CORS config intentionally disables CORS.
        if (is_array($paths) && count($paths) === 0) {
            return $next($request);
        }

        // Fallback to env if config wasn't populated for some reason.
        $enabled = env('CP_ENABLE_CORS', false);

        if (! $enabled) {
            return $next($request);
        }

        $handler = app(BaseHandleCors::class);

        return $handler->handle($request, $next);
    }
}
