AppserverIo\Appserver\ServletEngine\Http\Request::prepare PHP Méthode

prepare() public méthode

Prepares the request instance.
public prepare ( ) : void
Résultat void
    public function prepare()
    {
        // prepare the context path
        $contextPath = str_replace($this->getContext()->getAppBase(), '', $this->getContext()->getWebappPath());
        // set the context path
        $this->setContextPath($contextPath);
        // Fixed #735 - Endless Loop for URLs without servlet name
        // Load the request URI and query string from the server vars, because we have to
        // take care about changes from other modules like directory or rewrite module!
        $uri = $this->getRequestUri();
        $queryString = $this->getQueryString();
        // get uri without querystring
        $uriWithoutQueryString = str_replace('?' . $queryString, '', $uri);
        // initialize the path information and the directory to start with
        list($dirname, $basename, $extension) = array_values(pathinfo($uriWithoutQueryString));
        // make the registered handlers local
        $handlers = $this->getHandlers();
        // descent the directory structure down to find the (almost virtual) servlet file
        do {
            // bingo we found a (again: almost virtual) servlet file
            if (isset($handlers[".{$extension}"])) {
                // prepare the servlet path (we've to take care, because the
                // pathinfo() function converts / to \ on Windows OS
                if ($dirname === DIRECTORY_SEPARATOR) {
                    $servletPath = '/' . $basename;
                } else {
                    $servletPath = $dirname . '/' . $basename;
                }
                // we set the basename, because this is the servlet path
                $this->setServletPath($servletPath);
                // we set the path info, what is the request URI with stripped dir- and basename
                $this->setPathInfo(str_replace($servletPath, '', $uriWithoutQueryString));
                // we've found what we were looking for, so break here
                break;
            }
            // break if we finally can't find a servlet to handle the request
            if ($dirname === '/') {
                throw new ServletException(sprintf('Can\'t find a handler for URI %s, either ', $uri));
            }
            // descend down the directory tree
            list($dirname, $basename, $extension) = array_values(pathinfo($dirname));
        } while ($dirname !== false);
        // stop until we reached the root of the URI
        // prepare and set the servlet path
        $this->setServletPath(str_replace($contextPath, '', $this->getServletPath()));
        // prepare the base modifier which allows our apps to provide a base URL
        $webappsDir = str_replace($this->getContext()->getBaseDirectory(), '', $this->getContext()->getAppBase());
        $relativeRequestPath = strstr($this->getDocumentRoot(), $webappsDir);
        $proposedBaseModifier = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($webappsDir, '', $relativeRequestPath));
        //  prepare the base modifier
        if (strpos($proposedBaseModifier, $contextPath) === 0) {
            $this->setBaseModifier('');
        } else {
            $this->setBaseModifier($contextPath);
        }
    }

Usage Example

 /**
  * Process servlet request.
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param integer                                                $hook           The current hook to process logic for
  *
  * @return boolean
  *
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // if false hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // check if we are the handler that has to process this request
     if ($requestContext->getServerVar(ServerVars::SERVER_HANDLER) !== $this->getModuleName()) {
         return;
     }
     // load the application associated with this request
     $application = $this->findRequestedApplication($requestContext);
     $application->registerClassLoaders();
     // check if the application has already been connected
     if ($application->isConnected() === false) {
         throw new \Exception(sprintf('Application %s has not connected yet', $application->getName()), 503);
     }
     // create a copy of the valve instances
     $valves = $this->valves;
     $handlers = $this->handlers;
     // create a new request instance from the HTTP request
     $servletRequest = new Request();
     $servletRequest->injectHandlers($handlers);
     $servletRequest->injectHttpRequest($request);
     $servletRequest->injectServerVars($requestContext->getServerVars());
     $servletRequest->init();
     // initialize servlet response
     $servletResponse = new Response();
     $servletResponse->init();
     // load the session and the authentication manager
     $sessionManager = $application->search(SessionManagerInterface::IDENTIFIER);
     $authenticationManager = $application->search(AuthenticationManagerInterface::IDENTIFIER);
     // inject the sapplication and servlet response
     $servletRequest->injectContext($application);
     $servletRequest->injectResponse($servletResponse);
     $servletRequest->injectSessionManager($sessionManager);
     $servletRequest->injectAuthenticationManager($authenticationManager);
     // prepare the request instance
     $servletRequest->prepare();
     // initialize static request and application context
     RequestHandler::$requestContext = $servletRequest;
     RequestHandler::$applicationContext = $application;
     // process the valves
     foreach ($valves as $valve) {
         $valve->invoke($servletRequest, $servletResponse);
         if ($servletRequest->isDispatched() === true) {
             break;
         }
     }
     // copy response values to the HTTP response
     $response->setState($servletResponse->getState());
     $response->setVersion($servletResponse->getVersion());
     $response->setStatusCode($servletResponse->getStatusCode());
     $response->setStatusReasonPhrase($servletResponse->getStatusReasonPhrase());
     // copy the body content to the HTTP response
     $response->appendBodyStream($servletResponse->getBodyStream());
     // copy headers to the HTTP response
     foreach ($servletResponse->getHeaders() as $headerName => $headerValue) {
         $response->addHeader($headerName, $headerValue);
     }
     // copy cookies to the HTTP response
     $response->setCookies($servletResponse->getCookies());
     // append the servlet engine's signature
     $response->addHeader(Protocol::HEADER_X_POWERED_BY, get_class($this), true);
     // set response state to be dispatched after this without calling other modules process
     $response->setState(HttpResponseStates::DISPATCH);
 }