Skip to content

Http interceptors

Http interceptors can modify request and response data and read a handler information. Should return true when a validation, modification or what a user want is ok otherwise false. When action is valid http manager runs a controller handler. Best practice is to throw exception when somehitng is bad so the exception handler will be called.

Use cases

  • providing authentication and authorization
  • modifying and reading handler informations

Example

CustomAnnotation

php
namespace Avocado\Tests\Unit\Application;

use Attribute;

#[Attribute]
class CustomAnnotation {}

CustomAnnotationInterceptor.php

php
#[Resource]
#[PreProcessor]
class CustomAnnotationInterceptor implements WebRequestAnnotationInterceptorAdapter {
    public function __construct() {}

    /**
     * @throws Exception
     */
    function preHandle(HttpRequest $request, HttpResponse $response, WebRequestHandler $handler): bool {
        if ($handler->hasAnnotation(CustomAnnotation::class)) {
            // action when handler is annotated with `CustomAnnotation` class
            throw new Exception("Hello from interceptor");
        }

        return true;
    }
}

SomeController.php

php
class SomeController {
    #[CustomAnnotation]
    #[GetMapping("/interceptor-test")]
    public function interceptorTest(): array {
        return [];
    }
}