?php

declare(strict_types=1);

namespace Vendor\Extension\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\Stream;
use voku\helper\HtmlMin;

class HtmlMinifier implements MiddlewareInterface
{
    protected function createStream(string $content): Stream
    {
        $body = new Stream('php://temp', 'wb+');
        $body->write($content);
        $body->rewind();

        return $body;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        if (stripos($response->getHeaderLine('Content-Type'), 'text/html') === 0) {

            // Minify content
            $content = (new HtmlMin)->minify((string)$response->getBody());

            return $response->withBody($this->createStream($content));
        }

        return $response;
    }
}