Completed
Push — master ( 6b8416...c520c0 )
by Filipe
02:12
created

CallableMiddleware::execute()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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