Phred/src/Mvc/ViewController.php

43 lines
1.4 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Phred\Mvc;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\ResponseInterface;
abstract class ViewController extends Controller
{
private Psr17Factory $psr17;
public function __construct()
{
$this->psr17 = new Psr17Factory();
}
/**
* Return an HTML response with the provided content.
*/
protected function html(string $content, int $status = 200, array $headers = []): ResponseInterface
{
$response = $this->psr17->createResponse($status)->withHeader('Content-Type', 'text/html; charset=utf-8');
foreach ($headers as $k => $v) {
$response = $response->withHeader((string) $k, (string) $v);
}
$response->getBody()->write($content);
return $response;
}
/**
* Convenience to render a module View and return an HTML response.
* The `$template` is optional; when omitted (null), the view should use its default template.
*/
protected function renderView(View $view, array $data = [], ?string $template = null, int $status = 200, array $headers = []): ResponseInterface
{
// Delegate template selection to the View; when $template is null,
// the View may use its default template.
$markup = $view->render($data, $template);
return $this->html($markup, $status, $headers);
}
}