Implement request handler for maintenance mode

This commit is contained in:
Franz Liedke 2018-08-22 00:07:50 +02:00
parent 7439069fe2
commit 59b1ca9b7c
No known key found for this signature in database
GPG Key ID: 9A0231A879B055F4
2 changed files with 59 additions and 21 deletions

View File

@ -18,9 +18,7 @@ use Flarum\Foundation\Console\CacheClearCommand;
use Flarum\Foundation\Console\InfoCommand;
use Flarum\Http\Middleware\DispatchRoute;
use Flarum\Settings\SettingsRepositoryInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Stratigility\MiddlewarePipe;
use function Zend\Stratigility\middleware;
use function Zend\Stratigility\path;
class InstalledApp implements AppInterface
@ -47,7 +45,7 @@ class InstalledApp implements AppInterface
public function getRequestHandler()
{
if ($this->inMaintenanceMode()) {
return $this->getMaintenanceHandler();
return new MaintenanceModeHandler();
} elseif ($this->needsUpdate()) {
return $this->getUpdaterHandler();
}
@ -66,24 +64,6 @@ class InstalledApp implements AppInterface
return $this->config['offline'] ?? false;
}
/**
* @return \Psr\Http\Server\RequestHandlerInterface
*/
private function getMaintenanceHandler()
{
$pipe = new MiddlewarePipe;
$pipe->pipe(middleware(function () {
// FIXME: Fix path to 503.html
// TODO: FOR API render JSON-API error document for HTTP 503
return new HtmlResponse(
file_get_contents(__DIR__.'/../../503.html'), 503
);
}));
return $pipe;
}
private function needsUpdate(): bool
{
$settings = $this->laravel->make(SettingsRepositoryInterface::class);

View File

@ -0,0 +1,58 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Foundation;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Tobscure\JsonApi\Document;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
class MaintenanceModeHandler implements RequestHandlerInterface
{
const MESSAGE = 'Currently down for maintenance. Please come back later.';
/**
* Handle the request and return a response.
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
// Special handling for API requests: they get a proper API response
if ($this->isApiRequest($request)) {
return $this->apiResponse();
}
// By default, return a simple text message.
return new HtmlResponse(self::MESSAGE, 503);
}
private function isApiRequest(ServerRequestInterface $request): bool
{
return str_contains(
$request->getHeaderLine('Accept'),
'application/vnd.api+json'
);
}
private function apiResponse(): ResponseInterface
{
return new JsonResponse(
(new Document)->setErrors([
'status' => '503',
'title' => self::MESSAGE
]),
503,
['Content-Type' => 'application/vnd.api+json']
);
}
}