Skip to content

Latest commit

 

History

History
84 lines (67 loc) · 2.53 KB

middleware.md

File metadata and controls

84 lines (67 loc) · 2.53 KB

Ulrack Web - Middleware

Middleware is used to perform additional checks in routers. Middleware implements the MiddlewareInterface. It uses two methods for this validation, one is to perform the check, and the other one is used for formulating the correct response. An example middleware which does a check for a header would be:

<?php

namespace MyProject\MyPackage\Component\Middleware;

use Ulrack\Web\Common\Endpoint\InputInterface;
use Ulrack\Web\Common\Endpoint\OutputInterface;
use Ulrack\Web\Common\Middleware\MiddlewareInterface;

class HeaderCheckingMiddleware implements MiddlewareInterface
{
    /**
     * Retrieves the error code for the middleware if it does not pass.
     *
     * @return int
     */
    public function getErrorCode(): int
    {
        return 401;
    }

    /**
     * Performs additional checks on the route.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return bool
     */
    public function pass(
        InputInterface $input,
        OutputInterface $output
    ): bool {
        $request = $input->getRequest();

        if (
            $request->hasHeader('Authorization') &&
            $request->getHeader('Authorization') === 'my-auth-code'
        ) {
            return true;
        }

        return false;
    }
}

This middleware could then be used in a MiddlewareRouter to perform the check when a request is made to another router.

The following implementations for middleware are provided in this package:

Further reading

Back to usage index

Request codecs

Error

Endpoint

Routers