Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
/**
4
 * Slim Framework (https://slimframework.com)
5
 *
6
 * @license https://github.com/slimphp/Slim/blob/4.x/LICENSE.md (MIT License)
7
 */
8
 
9
declare(strict_types=1);
10
 
11
namespace Slim\Middleware;
12
 
13
use InvalidArgumentException;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use Psr\Http\Message\StreamFactoryInterface;
17
use Psr\Http\Server\MiddlewareInterface;
18
use Psr\Http\Server\RequestHandlerInterface;
19
use Throwable;
20
 
21
use function in_array;
22
use function ob_end_clean;
23
use function ob_get_clean;
24
use function ob_start;
25
 
26
class OutputBufferingMiddleware implements MiddlewareInterface
27
{
28
    public const APPEND = 'append';
29
    public const PREPEND = 'prepend';
30
 
31
    protected StreamFactoryInterface $streamFactory;
32
 
33
    protected string $style;
34
 
35
    /**
36
     * @param string $style Either "append" or "prepend"
37
     */
38
    public function __construct(StreamFactoryInterface $streamFactory, string $style = 'append')
39
    {
40
        $this->streamFactory = $streamFactory;
41
        $this->style = $style;
42
 
43
        if (!in_array($style, [static::APPEND, static::PREPEND], true)) {
44
            throw new InvalidArgumentException("Invalid style `{$style}`. Must be `append` or `prepend`");
45
        }
46
    }
47
 
48
    /**
49
     * @throws Throwable
50
     */
51
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
52
    {
53
        try {
54
            ob_start();
55
            $response = $handler->handle($request);
56
            $output = ob_get_clean();
57
        } catch (Throwable $e) {
58
            ob_end_clean();
59
            throw $e;
60
        }
61
 
62
        if (!empty($output)) {
63
            if ($this->style === static::PREPEND) {
64
                $body = $this->streamFactory->createStream();
65
                $body->write($output . $response->getBody());
66
                $response = $response->withBody($body);
67
            } elseif ($this->style === static::APPEND && $response->getBody()->isWritable()) {
68
                $response->getBody()->write($output);
69
            }
70
        }
71
 
72
        return $response;
73
    }
74
}