<?php

namespace HS\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'saml2/*',
        'sessioncheck',
        'api*',
    ];

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        $exceptions = array_merge($this->getConfiguredCSRFRouteExceptions(), $this->except);

        foreach ($exceptions as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->fullUrlIs($except) || $request->is($except)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get CSRF route exceptions from environment configuration
     * @return array
     */
    protected function getConfiguredCSRFRouteExceptions()
    {
        $routeList = explode(',', config('helpspot.disable_csrf', ''));

        if (is_array($routeList)) {
            return collect($routeList)->filter(function($route) {
                return ! empty(trim($route));
            })->map(function($route) {
                return trim($route);
            })->toArray();
        }

        return [];
    }
}
