-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhpRouteHandler.php
More file actions
49 lines (38 loc) · 1.38 KB
/
Copy pathPhpRouteHandler.php
File metadata and controls
49 lines (38 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php declare(strict_types=1);
namespace tebe\zack\routing;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class PhpRouteHandler
{
private ?ContainerBuilder $container;
public function __invoke(Request $request): Response
{
$this->container = $request->attributes->get('_container');
$path = $request->attributes->get('_path');
if ($path === null) {
throw new \Exception('Attribute _path not found in request attributes');
}
if (!file_exists($path)) {
throw new \Exception('PHP file not found for path: ' . $path);
}
$response = require $path;
if (!$response instanceof Response) {
throw new \Exception('PHP file must return a response object: ' . $path);
}
return $response;
}
public function html(string $template, array $context = []): Response
{
$twig = $this->container->get('twig');
$html = $twig->render($template, $context);
return new Response($html, 200);
}
public function json(array $context = []): Response
{
$json = json_encode($context, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
return new Response($json, 200, [
'Content-Type' => 'application/json',
]);
}
}