Completed
Push — master ( 3334ca...4b28b4 )
by Tim
31:46 queued 17:03
created

CleanHtmlMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 42
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 22 4
1
<?php
2
3
namespace HTML\Sourceopt\Middleware;
4
5
use HTML\Sourceopt\Service\CleanHtmlService;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use TYPO3\CMS\Core\Http\Stream;
11
use TYPO3\CMS\Core\Utility\GeneralUtility;
12
13
class CleanHtmlMiddleware implements MiddlewareInterface
14
{
15
    /**
16
     * @var CleanHtmlService
17
     */
18
    protected $cleanHtmlService = null;
19
20
    public function __construct()
21
    {
22
        $this->cleanHtmlService = GeneralUtility::makeInstance(CleanHtmlService::class);
23
    }
24
25
    /**
26
     * Clean the HTML output
27
     *
28
     * @param ServerRequestInterface $request
29
     * @param RequestHandlerInterface $handler
30
     * @return ResponseInterface
31
     */
32
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
33
    {
34
        $response = $handler->handle($request);
35
36
        if (
37
            !($response instanceof \TYPO3\CMS\Core\Http\NullResponse)
38
            && $GLOBALS['TSFE'] instanceof \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
39
            && $GLOBALS['TSFE']->isOutputting()) {
40
41
            $processedHtml = $this->cleanHtmlService->clean(
42
                $response->getBody()->__toString(),
43
                $GLOBALS['TSFE']->config['config']['sourceopt.']
44
            );
45
46
            // Replace old body with $processedHtml
47
            $responseBody = new Stream('php://temp', 'rw');
48
            $responseBody->write($processedHtml);
49
            $response = $response->withBody($responseBody);
50
        }
51
52
        return $response;
53
    }
54
}
55