Created
October 7, 2024 12:29
-
-
Save sorenmalling/ac45fbcdf539604d8aa58ef6a1f82060 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace UniversityOfCopenhagen\Mirror\Middleware; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use Psr\Http\Message\UriInterface; | |
use Psr\Http\Server\MiddlewareInterface; | |
use Psr\Http\Server\RequestHandlerInterface; | |
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface; | |
use TYPO3\CMS\Core\Http\HtmlResponse; | |
use TYPO3\CMS\Core\Http\RequestFactory; | |
use TYPO3\CMS\Core\Http\Uri; | |
final class Mirror implements MiddlewareInterface | |
{ | |
public function __construct( | |
private RequestFactory $requestFactory, | |
private FrontendInterface $cache | |
) {} | |
protected static string $host = 'domain.dk'; | |
protected static array $pathMapping = [ | |
'/' => 'https://oldcms.domain.dk/', | |
'/english' => 'https://oldcms.domain.dk/english' | |
]; | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
{ | |
$uri = $request->getUri(); | |
if ( | |
($uri->getHost() === self::$host || $uri->getHost() === 'www.' . self::$host) && | |
in_array($uri->getPath(), array_keys(self::$pathMapping)) | |
) { | |
$body = $this->cache->get(sha1((string) $uri)); | |
if ($body === false) { | |
$body = $this->fetch( | |
new Uri(self::$pathMapping[$uri->getPath()]) | |
); | |
$this->cache->set( | |
sha1((string) $uri), | |
$body, | |
[], | |
(60*60*24) | |
); | |
} | |
return new HtmlResponse($body); | |
} else { | |
return $handler->handle($request); | |
} | |
} | |
private function fetch(UriInterface $uri): string | |
{ | |
$response = $this->requestFactory->request( | |
uri: (string) $uri | |
); | |
return $response->getBody()->getContents(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment