<?php
namespace Mogic\Extension;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AppendDot implements \Psr\Http\Server\MiddlewareInterface
{
    /**
     * Modify the generated HTML by adding a dot before the closing body tag.
     */
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);

        $newContent = str_replace('</body>', '.</body>', (string) $response->getBody());

        //stream body code copied from HtmlResponse
        $body = new \TYPO3\CMS\Core\Http\Stream('php://temp', 'wb+');
        $body->write($newContent);
        $body->rewind();

        return $response->withBody($body);
    }
}