summaryrefslogtreecommitdiff
path: root/src/Middleware/ResolvesMiddlewareTrait.php
blob: 76557ce6eed5bf5387bc5f0a254fd3d4670753d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php

namespace Engelsystem\Middleware;

use Engelsystem\Application;
use InvalidArgumentException;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

trait ResolvesMiddlewareTrait
{
    /**
     * Resolve the middleware with the container
     *
     * @param string|callable|MiddlewareInterface|RequestHandlerInterface $middleware
     * @return MiddlewareInterface|RequestHandlerInterface
     */
    protected function resolveMiddleware($middleware)
    {
        if ($this->isMiddleware($middleware)) {
            return $middleware;
        }

        if (!property_exists($this, 'container') || !$this->container instanceof Application) {
            throw new InvalidArgumentException('Unable to resolve middleware');
        }

        /** @var Application $container */
        $container = $this->container;

        if (is_string($middleware)) {
            $middleware = $container->make($middleware);
        }

        if (is_callable($middleware)) {
            $middleware = $container->make(CallableHandler::class, ['callable' => $middleware]);
        }

        if ($this->isMiddleware($middleware)) {
            return $middleware;
        }

        throw new InvalidArgumentException('Unable to resolve middleware');
    }

    /**
     * Checks if the given object is a middleware or middleware or request handler
     *
     * @param mixed $middleware
     * @return bool
     */
    protected function isMiddleware($middleware)
    {
        return ($middleware instanceof MiddlewareInterface || $middleware instanceof RequestHandlerInterface);
    }
}