<?php

namespace apexl\Io\middleware\accessRequest;

use apexl\Io\services\pathUtility;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Exception\HttpNotFoundException;
use Slim\Routing\RouteContext;

class accessRequest implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        $routeContext = RouteContext::fromRequest($request);
        $route = $routeContext->getRoute();

        // return NotFound for non existent route
        if (empty($route)) {
            throw new HttpNotFoundException($request);
        }

        //set the current route object into path so we can access it anywhere in the app.
        $path = pathUtility::getInstance();
        $path->setCurrentRoute($route);

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