CallableMiddleware   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 58
rs 10
c 2
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A execute() 0 19 6
A process() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of slick/http
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Slick\Http\Server\Middleware;
13
14
use Psr\Http\Server\MiddlewareInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Http\Server\RequestHandlerInterface;
18
use Slick\Http\Message\Response;
19
use Slick\Http\Message\Stream\TextStream;
20
use Slick\Http\Server\Exception\UnexpectedValueException;
21
22
/**
23
 * Callable Middleware
24
 *
25
 * @package Slick\Http\Server\Middleware
26
*/
27
class CallableMiddleware implements MiddlewareInterface
28
{
29
    /**
30
     * @var callable
31
     */
32
    private $callable;
33
34
    /**
35
     * Creates a callable Middleware
36
     *
37
     * @param callable $callable
38
     */
39
    public function __construct(callable $callable)
40
    {
41
        $this->callable = $callable;
42
    }
43
44
    /**
45
     * @param callable $callable
46
     * @param array<mixed>    $arguments
47
     *
48
     * @return ResponseInterface
49
     */
50
    public static function execute(callable $callable, array $arguments): ResponseInterface
51
    {
52
        $return = \call_user_func_array($callable, $arguments);
53
54
        if ($return instanceof ResponseInterface) {
55
            return $return;
56
        }
57
58
        $canBeUsedAsText = \is_null($return)
59
            || \is_scalar($return)
60
            || (\is_object($return) && method_exists($return, '__toString'));
61
62
        if (! $canBeUsedAsText) {
63
            throw new UnexpectedValueException(
64
                'The value returned must be scalar or an object with __toString method'
65
            );
66
        }
67
68
        return new Response(200, new TextStream((string) $return));
69
    }
70
71
    /**
72
     * Process an incoming server request and return a response, optionally delegating
73
     * response creation to an handler.
74
     *
75
     * @param ServerRequestInterface $request
76
     * @param RequestHandlerInterface $handler
77
     *
78
     * @return ResponseInterface
79
     */
80
    public function process(
81
        ServerRequestInterface $request,
82
        RequestHandlerInterface $handler
83
    ): ResponseInterface {
84
        return self::execute($this->callable, [$request, $handler]);
85
    }
86
}
87