Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
ResolvesMiddlewareTrait
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
2 / 2
9
100.00% covered (success)
100.00%
1 / 1
 resolveMiddleware
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 isMiddleware
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Middleware;
6
7use Engelsystem\Application;
8use InvalidArgumentException;
9use Psr\Http\Server\MiddlewareInterface;
10use Psr\Http\Server\RequestHandlerInterface;
11
12trait ResolvesMiddlewareTrait
13{
14    /**
15     * Resolve the middleware with the container
16     */
17    protected function resolveMiddleware(
18        string|callable|array|MiddlewareInterface|RequestHandlerInterface $middleware
19    ): MiddlewareInterface|RequestHandlerInterface {
20        if ($this->isMiddleware($middleware)) {
21            return $middleware;
22        }
23
24        if (!property_exists($this, 'container') || !$this->container instanceof Application) {
25            throw new InvalidArgumentException('Unable to resolve container for middleware');
26        }
27
28        /** @var Application $container */
29        $container = $this->container;
30
31        if (is_string($middleware)) {
32            $middleware = $container->make($middleware);
33        }
34
35        if (is_callable($middleware)) {
36            $middleware = $container->make(CallableHandler::class, ['callable' => $middleware]);
37        }
38
39        if ($this->isMiddleware($middleware)) {
40            return $middleware;
41        }
42
43        throw new InvalidArgumentException('Unable to resolve middleware or callable');
44    }
45
46    /**
47     * Checks if the given object is a middleware or request handler
48     */
49    protected function isMiddleware(mixed $middleware): bool
50    {
51        return ($middleware instanceof MiddlewareInterface || $middleware instanceof RequestHandlerInterface);
52    }
53}