Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
CallableHandler
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
5 / 5
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 process
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 getCallable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Middleware;
6
7use Engelsystem\Container\Container;
8use Engelsystem\Http\Response;
9use InvalidArgumentException;
10use Psr\Http\Message\ResponseInterface;
11use Psr\Http\Message\ServerRequestInterface;
12use Psr\Http\Server\MiddlewareInterface;
13use Psr\Http\Server\RequestHandlerInterface;
14
15/**
16 * Wraps a callable to be used to respond / as a middleware
17 */
18class CallableHandler implements MiddlewareInterface, RequestHandlerInterface
19{
20    /** @var callable */
21    protected $callable;
22
23    protected ?Container $container = null;
24
25    /**
26     * @param callable  $callable The callable that should be wrapped
27     */
28    public function __construct(callable $callable, Container $container = null)
29    {
30        $this->callable = $callable;
31        $this->container = $container;
32    }
33
34    /**
35     * Process an incoming server request and return a response, optionally delegating
36     * response creation to a handler.
37     */
38    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39    {
40        return $this->execute([$request, $handler]);
41    }
42
43    /**
44     * Handle the request and return a response.
45     */
46    public function handle(ServerRequestInterface $request): ResponseInterface
47    {
48        return $this->execute([$request]);
49    }
50
51    /**
52     * Execute the callable and return a response
53     */
54    protected function execute(array $arguments = []): ResponseInterface
55    {
56        $return = call_user_func_array($this->callable, $arguments);
57
58        if ($return instanceof ResponseInterface) {
59            return $return;
60        }
61
62        if (!$this->container instanceof Container) {
63            throw new InvalidArgumentException('Unable to resolve response');
64        }
65
66        /** @var Response $response */
67        $response = $this->container->get('response');
68        return $response->withContent($return);
69    }
70
71    public function getCallable(): callable
72    {
73        return $this->callable;
74    }
75}