From 10504d9549f24c0e103d4b22e7d881ff85c2be07 Mon Sep 17 00:00:00 2001 From: markhuot Date: Tue, 31 Oct 2023 03:05:16 -0400 Subject: [PATCH] fix Twig globals not being reset each request, and handle cp/site Twig instances --- src/http/RequestBuilder.php | 6 ------ src/http/RequestHandler.php | 20 ++++++++++++++++++-- tests/templates/current-user.twig | 1 + 3 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 tests/templates/current-user.twig diff --git a/src/http/RequestBuilder.php b/src/http/RequestBuilder.php index a58e4b7..d1f47dc 100644 --- a/src/http/RequestBuilder.php +++ b/src/http/RequestBuilder.php @@ -86,12 +86,6 @@ public function send(): TestableResponse protected function setGlobals() { - $view = \Craft::$app->getView(); - $globals = (new Extension($view, $view->getTwig()))->getGlobals(); - foreach ($globals as $key => $value) { - $view->getTwig()->addGlobal($key, $value); - } - $this->originalGlobals['_POST'] = array_merge($_POST); $this->originalGlobals['_SERVER'] = array_merge($_SERVER); $_SERVER['HTTP_METHOD'] = $this->method; diff --git a/src/http/RequestHandler.php b/src/http/RequestHandler.php index 26fe2cf..7a572a2 100644 --- a/src/http/RequestHandler.php +++ b/src/http/RequestHandler.php @@ -2,6 +2,7 @@ namespace markhuot\craftpest\http; +use craft\web\twig\Extension; use markhuot\craftpest\http\requests\WebRequest; use markhuot\craftpest\web\TestableResponse; use Twig\Error\RuntimeError; @@ -81,10 +82,11 @@ protected function handleException(\Throwable $exception, WebRequest $request): return $response; } - private function registerWithCraft($request): void + protected function registerWithCraft($request): void { + // Don't run the queue automatically, because it injects JS in to pages that might not be expecting + // them under test $this->app->getConfig()->getGeneral()->runQueueAutomatically = false; - $this->app->getView()->setTemplateMode($request->isCpRequest ? 'cp' : 'site'); // The next request $this->app->set('request', $request); @@ -115,5 +117,19 @@ private function registerWithCraft($request): void 'ruleConfig' => ['class' => \craft\web\UrlRule::class], ], ]); + + // Pull out our view service + $view = \Craft::$app->getView(); + + // Set the correct template mode + $view->setTemplateMode($request->isCpRequest ? 'cp' : 'site'); + + // Update the Twig globals. Normally PHP/Craft operate in a single request/response + // lifecycle. However, because we're sending multiple requests through a single + // Craft instance we need to manually update the globals + $globals = (new Extension($view, $view->getTwig()))->getGlobals(); + foreach ($globals as $key => $value) { + $view->getTwig()->addGlobal($key, $value); + } } } diff --git a/tests/templates/current-user.twig b/tests/templates/current-user.twig new file mode 100644 index 0000000..e933cfa --- /dev/null +++ b/tests/templates/current-user.twig @@ -0,0 +1 @@ +{{ currentUser.getId()|default }}