33namespace tebe \zack \routing ;
44
55use Symfony \Component \DependencyInjection \ContainerBuilder ;
6+ use Symfony \Component \HttpFoundation \RedirectResponse ;
67use Symfony \Component \HttpFoundation \Request ;
78use Symfony \Component \HttpFoundation \Response ;
89
10+ use function tebe \zack \html_extract_title ;
11+
912class PhpRouteHandler
1013{
1114 private ?ContainerBuilder $ container ;
@@ -23,19 +26,30 @@ public function __invoke(Request $request): Response
2326 throw new \Exception ('PHP file not found for path: ' . $ path );
2427 }
2528
26- $ response = require $ path ;
29+ ob_start ();
30+ $ returnValue = require $ path ;
31+ $ outputValue = ob_get_clean ();
2732
28- if (!$ response instanceof Response) {
29- throw new \Exception ('PHP file must return a response object: ' . $ path );
33+ if ($ returnValue === 1 && is_string ($ outputValue )) {
34+ $ title = html_extract_title ($ outputValue , basename ($ path ));
35+ return $ this ->html ('route-handler.html.twig ' , ['title ' => $ title , 'html ' => $ outputValue ]);
36+ } elseif (is_string ($ returnValue )) {
37+ if (is_string ($ outputValue ) && strlen ($ outputValue ) > 0 ) {
38+ throw new \Exception ('In the PHP file the return value must be omitted if an output was made via echo: ' . $ path );
39+ }
40+ return new Response ($ returnValue , 200 );
41+ } elseif (is_array ($ returnValue )) {
42+ return $ this ->json ($ returnValue );
43+ } elseif ($ returnValue instanceof Response) {
44+ return $ returnValue ;
45+ } else {
46+ throw new \Exception ('The PHP file must output something or return a string, an array or a response object: ' . $ path );
3047 }
31-
32- return $ response ;
3348 }
3449
3550 public function html (string $ template , array $ context = []): Response
3651 {
37- $ twig = $ this ->container ->get ('twig ' );
38- $ html = $ twig ->render ($ template , $ context );
52+ $ html = $ this ->render ($ template , $ context );
3953 return new Response ($ html , 200 );
4054 }
4155
@@ -46,4 +60,15 @@ public function json(array $context = []): Response
4660 'Content-Type ' => 'application/json ' ,
4761 ]);
4862 }
63+
64+ public function redirect (string $ url , int $ status = 302 ): Response
65+ {
66+ return new RedirectResponse ($ url , $ status );
67+ }
68+
69+ public function render (string $ template , array $ context = []): string
70+ {
71+ $ twig = $ this ->container ->get ('twig ' );
72+ return $ twig ->render ($ template , $ context );
73+ }
4974}
0 commit comments