Core/src/Controllers/HtmlController.php

73 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Benzine\Controllers;
2020-07-27 02:44:36 +00:00
use DebugBar\DebugBar;
use Monolog\Logger;
2020-06-19 07:53:59 +00:00
use Slim\Psr7\Request;
use Slim\Psr7\Response;
use Slim\Views\Twig;
abstract class HtmlController extends Controller
{
2020-07-27 02:44:36 +00:00
protected Twig $twig;
protected DebugBar $debugBar;
2020-08-27 17:25:48 +00:00
protected string $pageNotFoundTemplate = '404.html.twig';
public function __construct(
2020-07-27 02:44:36 +00:00
Twig $twig,
Logger $logger,
DebugBar $debugBar
) {
2020-07-27 02:44:36 +00:00
parent::__construct($logger);
$this->twig = $twig;
2020-07-27 02:44:36 +00:00
$this->debugBar = $debugBar;
}
protected function renderInlineCss(array $files)
{
$css = '';
foreach ($files as $file) {
$css .= file_get_contents($file);
}
return "<style>{$css}</style>";
}
protected function renderHtml(Request $request, Response $response, string $template, array $parameters = []): Response
{
// If the path ends in .json, return the parameters
if ('.json' == substr($request->getUri()->getPath(), -5, 5)) {
return $this->jsonResponse($parameters, $request, $response);
}
2020-06-18 17:24:31 +00:00
2020-07-27 02:44:36 +00:00
$renderStart = microtime(true);
$this->debugBar['time']->startMeasure('render', 'Time for rendering');
$response = $this->twig->render(
$response,
$template,
$parameters
2020-07-27 01:36:42 +00:00
)->withHeader('Content-Type', 'text/html');
2020-07-27 02:44:36 +00:00
$this->logger->debug(sprintf(
'Took %sms to render %s',
number_format((microtime(true) - $renderStart) * 1000, 2),
$template
));
$this->debugBar['time']->stopMeasure('render');
return $response;
}
2020-08-27 17:24:10 +00:00
protected function pageNotFound(): Response
{
$response = (parent::pageNotFound());
$response->withHeader('Content-Type', 'text/html');
$response->getBody()
2020-08-27 17:25:48 +00:00
->write($this->twig->fetch($this->pageNotFoundTemplate))
;
2020-08-27 17:24:10 +00:00
return $response;
}
}