-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathResourcePusher.php
More file actions
64 lines (60 loc) · 2.8 KB
/
ResourcePusher.php
File metadata and controls
64 lines (60 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types = 1);
namespace B13\Http2\Http;
/*
* This file is part of TYPO3 CMS-based extension "http2" by b13.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*/
use B13\Http2\Event\ProcessResourcesEvent;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
use TYPO3\CMS\Core\Http\NormalizedParams;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Takes existing accumulated resources and pushes them as HTTP2 <link> headers as middleware.
*
* This considers that everything is required, thus is marked as "preload", not via "prefetch".
*
* Also, it only tackles "script", "style", but we should incorporate font as well.
* See https://w3c.github.io/preload/#as-attribute
*/
class ResourcePusher implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if (($GLOBALS['TSFE'] ?? null) instanceof TypoScriptFrontendController) {
$resources = $GLOBALS['TSFE']->config['b13/http2'] ?? null;
/** @var NormalizedParams $normalizedParams */
$normalizedParams = $request->getAttribute('normalizedParams');
if (is_array($resources) && $normalizedParams->isHttps()) {
$eventDispatcher = GeneralUtility::makeInstance(EventDispatcher::class);
$event = $eventDispatcher->dispatch(new ProcessResourcesEvent($resources));
$resources = $event->getResources();
foreach ($resources['scripts'] ?? [] as $resource) {
$response = $this->addPreloadHeaderToResponse($response, $resource, 'script');
}
foreach ($resources['styles'] ?? [] as $resource) {
$response = $this->addPreloadHeaderToResponse($response, $resource, 'style');
}
}
}
return $response;
}
protected function addPreloadHeaderToResponse(ResponseInterface $response, string $uri, string $type): ResponseInterface
{
if(str_contains($uri, '.mjs')) {
return $response->withAddedHeader('Link', '<' . htmlspecialchars(PathUtility::getAbsoluteWebPath($uri)) . '>; rel=modulepreload; as=' . $type);
} else {
return $response->withAddedHeader('Link', '<' . htmlspecialchars(PathUtility::getAbsoluteWebPath($uri)) . '>; rel=preload; as=' . $type);
}
}
}