2024-05-16 01:42:24 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Slovocast\Controller;
|
|
|
|
|
|
|
|
use Psr\Http\Message\ResponseInterface as Response;
|
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
|
|
|
use Slim\Views\Twig;
|
|
|
|
use Slim\Routing\RouteContext;
|
|
|
|
|
|
|
|
abstract class Controller
|
|
|
|
{
|
|
|
|
protected Request $request;
|
|
|
|
protected Response $response;
|
|
|
|
protected array $args;
|
|
|
|
protected RouteContext $routeContext;
|
2024-05-23 00:39:33 +00:00
|
|
|
protected Twig $view;
|
2024-05-16 01:42:24 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Make the Class invokable and pass it into a route as its handler.
|
|
|
|
*
|
|
|
|
* @param Request $request
|
|
|
|
* @param Response $response
|
|
|
|
* @param array $args List of possible URL arguments
|
|
|
|
* @return Response
|
|
|
|
*/
|
|
|
|
public function __invoke(
|
|
|
|
Request $request,
|
|
|
|
Response $response,
|
|
|
|
array $args = []
|
|
|
|
): Response {
|
|
|
|
$this->request = $request;
|
|
|
|
$this->response = $response;
|
|
|
|
$this->args = $args;
|
|
|
|
$this->routeContext = RouteContext::fromRequest($this->request);
|
2024-05-23 00:39:33 +00:00
|
|
|
$this->view = Twig::fromRequest($request);
|
2024-05-16 01:42:24 +00:00
|
|
|
|
|
|
|
return $this->respond($request, $response);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Implement this method for handling the request.
|
|
|
|
*
|
|
|
|
* @return Response
|
|
|
|
*/
|
|
|
|
abstract public function respond(): Response;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Render the given Template.
|
|
|
|
*
|
|
|
|
* @param string $templateName The name of the template
|
|
|
|
* @param array $data The data for the template
|
|
|
|
* @return Response
|
|
|
|
*/
|
|
|
|
public function render(string $templateName, array $data = []): Response
|
|
|
|
{
|
2024-05-23 01:13:05 +00:00
|
|
|
return $this->view
|
|
|
|
->render($this->response, $templateName, $data)
|
|
|
|
->withHeader('Content-Type', 'text/html');
|
2024-05-23 00:39:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param string $html The raw Twig HTML to render
|
|
|
|
* @param array $data The data to injext into the HTML
|
|
|
|
* @return Response
|
|
|
|
*/
|
|
|
|
public function renderInline(string $html, array $data = []): Response
|
|
|
|
{
|
|
|
|
$renderedTemplate = $this->view->fetchFromString($html, $data);
|
|
|
|
$this->response->getBody()->write($renderedTemplate);
|
2024-05-23 01:13:05 +00:00
|
|
|
return $this->response->withHeader('Content-Type', 'text/html');
|
2024-05-23 00:39:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array|object $data The data to encode as JSON
|
|
|
|
* @return Response
|
|
|
|
*/
|
|
|
|
public function json(array|object $data): Response
|
|
|
|
{
|
|
|
|
$encodedData = json_encode($data);
|
|
|
|
$this->response->getBody()->write($encodedData);
|
|
|
|
return $this->response->withHeader('Content-Type', 'application/json');
|
2024-05-16 01:42:24 +00:00
|
|
|
}
|
|
|
|
}
|