Completed
Push — master ( db079f...ae1003 )
by Thomas
06:44 queued 04:24
created

HtmlMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace example\components;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
10
class HtmlMiddleware implements MiddlewareInterface
11
{
12
    const MODE_PREPEND = 0;
13
    const MODE_APPEND = 1;
14
15
    /**
16
     * @var string
17
     */
18
    private $string;
19
20
    /**
21
     * @var int
22
     */
23
    private $mode;
24
25
    /**
26
     * HtmlMiddleware constructor.
27
     * @param string $string
28
     * @param int $mode
29
     */
30
    public function __construct(string $string, int $mode = 0)
31
    {
32
        $this->string = $string;
33
        $this->mode = $mode;
34
    }
35
36
    /**
37
     * @param ServerRequestInterface $request
38
     * @param RequestHandlerInterface $handler
39
     * @return ResponseInterface
40
     */
41
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
42
    {
43
        $response = $handler->handle($request);
44
45
        // see: https://github.com/jshannon63/laravel-psr15-middleware/blob/master/src/exampleMiddleware.php
46
        $response->getBody()->rewind();
47
        $body = $response->getBody();
48
        $contents = $body->getContents();
49
50
        if (static::MODE_PREPEND == $this->mode) {
51
            $contents = str_replace(
52
                '<body>',
53
                "<body>".$this->string,
54
                $contents
55
            );
56
        }
57
        if (static::MODE_APPEND == $this->mode) {
58
            $contents = str_replace(
59
                '</body>',
60
                $this->string.'</body>',
61
                $contents
62
            );
63
        }
64
65
        $body->rewind();
66
        $body->write($contents);
67
68
        return $response->withBody($body);
69
    }
70
}
71