EchoBodyMiddleware::process()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 3
rs 10
1
<?php
2
3
/**
4
 * This file is part of coisa/http.
5
 *
6
 * (c) Felipe Sayão Lobato Abreu <[email protected]>
7
 *
8
 * This source file is subject to the license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
declare(strict_types=1);
13
14
namespace CoiSA\Http\Middleware;
15
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Http\Message\ServerRequestInterface;
18
use Psr\Http\Server\MiddlewareInterface;
19
use Psr\Http\Server\RequestHandlerInterface;
20
21
/**
22
 * Class EchoBodyMiddleware
23
 *
24
 * @package CoiSA\Http\Middleware
25
 */
26
final class EchoBodyMiddleware implements MiddlewareInterface
27
{
28
    /**
29
     * @const string
30
     */
31
    const DEFAULT_BUFFER_SIZE = 1024 * 8;
32
33
    /**
34
     * @var int
35
     */
36
    private $bufferSize;
37
38
    /**
39
     * EchoBodyMiddleware constructor.
40
     *
41
     * @param int $bufferSize
42
     */
43 4
    public function __construct(int $bufferSize = self::DEFAULT_BUFFER_SIZE)
44
    {
45 4
        $this->bufferSize = $bufferSize;
46 4
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
52
    {
53 3
        $response = $handler->handle($request);
54 3
        $stream   = $response->getBody();
55
56 3
        if ($stream->isSeekable()) {
57 1
            $stream->rewind();
58
        }
59
60 3
        while (!$stream->eof()) {
61 3
            echo $stream->read($this->bufferSize);
62
        }
63
64 3
        return $response;
65
    }
66
}
67