Skip to content

Commit

Permalink
fix Twig globals not being reset each request, and handle cp/site Twi…
Browse files Browse the repository at this point in the history
…g instances
  • Loading branch information
markhuot committed Oct 31, 2023
1 parent fd62090 commit 10504d9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
6 changes: 0 additions & 6 deletions src/http/RequestBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
20 changes: 18 additions & 2 deletions src/http/RequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
}
}
1 change: 1 addition & 0 deletions tests/templates/current-user.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ currentUser.getId()|default }}

0 comments on commit 10504d9

Please sign in to comment.