99use BEAR \Resource \Code ;
1010use BEAR \Resource \RenderInterface ;
1111use BEAR \Resource \ResourceObject ;
12+ use Madapaja \TwigModule \Annotation \TwigRedirectPath ;
1213use Ray \Aop \WeavedInterface ;
1314use Twig \Environment ;
1415use Twig \Error \LoaderError ;
@@ -29,14 +30,23 @@ class TwigRenderer implements RenderInterface
2930 */
3031 public $ twig ;
3132
33+ /**
34+ * @var string
35+ */
36+ private $ redirectPage ;
37+
3238 /**
3339 * @var TemplateFinderInterface
3440 */
3541 private $ templateFinder ;
3642
37- public function __construct (Environment $ twig , TemplateFinderInterface $ templateFinder = null )
43+ /**
44+ * @TwigRedirectPath("redirectPage")
45+ */
46+ public function __construct (Environment $ twig , string $ redirectPage , TemplateFinderInterface $ templateFinder = null )
3847 {
3948 $ this ->twig = $ twig ;
49+ $ this ->redirectPage = $ redirectPage ;
4050 $ this ->templateFinder = $ templateFinder ?: new TemplateFinder ;
4151 }
4252
@@ -46,7 +56,14 @@ public function __construct(Environment $twig, TemplateFinderInterface $template
4656 public function render (ResourceObject $ ro )
4757 {
4858 $ this ->setContentType ($ ro );
49- $ ro ->view = $ this ->isNoContent ($ ro ) ? '' : $ this ->renderView ($ ro );
59+
60+ if ($ this ->isNoContent ($ ro )) {
61+ $ ro ->view = '' ;
62+ } elseif ($ this ->isRedirect ($ ro )) {
63+ $ ro ->view = $ this ->renderRedirectView ($ ro );
64+ } else {
65+ $ ro ->view = $ this ->renderView ($ ro );
66+ }
5067
5168 return $ ro ->view ;
5269 }
@@ -65,6 +82,13 @@ private function renderView(ResourceObject $ro)
6582 return $ template ? $ template ->render ($ this ->buildBody ($ ro )) : '' ;
6683 }
6784
85+ private function renderRedirectView (ResourceObject $ ro )
86+ {
87+ $ url = $ ro ->headers ['Location ' ];
88+
89+ return $ this ->twig ->render ($ this ->redirectPage , ['url ' => $ url ]);
90+ }
91+
6892 /**
6993 * @return null|\Twig\TemplateWrapper
7094 */
@@ -84,6 +108,17 @@ private function isNoContent(ResourceObject $ro) : bool
84108 return $ ro ->code === Code::NO_CONTENT || $ ro ->view === '' ;
85109 }
86110
111+ private function isRedirect (ResourceObject $ ro ) : bool
112+ {
113+ return \in_array ($ ro ->code , [
114+ Code::MOVED_PERMANENTLY ,
115+ Code::FOUND ,
116+ Code::SEE_OTHER ,
117+ Code::TEMPORARY_REDIRECT ,
118+ Code::PERMANENT_REDIRECT ,
119+ ], true ) && isset ($ ro ->headers ['Location ' ]);
120+ }
121+
87122 private function loadTemplate (ResourceObject $ ro ) : TemplateWrapper
88123 {
89124 $ loader = $ this ->twig ->getLoader ();
0 commit comments