1
0
mirror of https://github.com/flarum/core.git synced 2025-10-18 10:16:09 +02:00

Error handling: Rename renderers to formatters

Refs #1641.
This commit is contained in:
Franz Liedke
2019-08-20 17:48:09 +02:00
parent 41009dba74
commit 9f15e9ba86
10 changed files with 19 additions and 19 deletions

View File

@@ -0,0 +1,81 @@
<?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\ErrorHandling;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Symfony\Component\Translation\TranslatorInterface;
use Zend\Diactoros\Response\HtmlResponse;
class ViewFormatter implements HttpFormatter
{
/**
* @var ViewFactory
*/
protected $view;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var SettingsRepositoryInterface
*/
protected $settings;
public function __construct(ViewFactory $view, TranslatorInterface $translator, SettingsRepositoryInterface $settings)
{
$this->view = $view;
$this->translator = $translator;
$this->settings = $settings;
}
public function format(HandledError $error, Request $request): Response
{
$view = $this->view->make($this->determineView($error))
->with('error', $error->getError())
->with('message', $this->getMessage($error));
return new HtmlResponse($view->render(), $error->getStatusCode());
}
const ERRORS_WITH_VIEWS = ['csrf_token_mismatch', 'not_found'];
private function determineView(HandledError $error): string
{
$type = $error->getType();
if (in_array($type, self::ERRORS_WITH_VIEWS)) {
return "flarum.forum::error.$type";
} else {
return 'flarum.forum::error.default';
}
}
private function getMessage(HandledError $error)
{
return $this->getTranslationIfExists($error->getType())
?? $this->getTranslationIfExists('unknown')
?? 'An error occurred while trying to load this page.';
}
private function getTranslationIfExists(string $errorType)
{
$key = "core.views.error.$errorType";
$translation = $this->translator->trans($key, ['{forum}' => $this->settings->get('forum_title')]);
return $translation === $key ? null : $translation;
}
}