That would work and I have thought of other ways to approach this issue but I would really like to know how to get the globals to work with the new version and all…
For those that reading this post and would like to know how to add Global’s this is how
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Views\Twig;
use SlimSession\Helper;
class FlashMessageMiddleware extends Middleware
{
public function __invoke(Request $request, RequestHandler $handler): Response
{
/* @var Twig $view*/
$view = $this->container->get("view");
/* @var Helper $session*/
$session = $this->container->get("session");
if ($session->exists('slimFlash') && is_array($session->get('slimFlash'))) {
$view->getEnvironment()->addGlobal(
'flash',
$session->get('slimFlash')
);
}
$session->delete('slimFlash');
return $handler->handle($request);
}
}
Can somebody please explain to me why the addGlobal() method of the Twig/Environment class throws an exception if a Global array key DOESN’T exist? Shouldn’t we be throwing the exception if the array key DOES exist? Seems like a bug, unless I’m not understanding something… The line in question is currently on line 906, I believe.
/**
* Registers a Global.
*
* New globals can be added before compiling or rendering a template;
* but after, you can only update existing globals.
*
* @param string $name The global name
* @param mixed $value The global value
*/
public function addGlobal($name, $value)
{
if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) {
throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
}
if (null !== $this->resolvedGlobals) {
$this->resolvedGlobals[$name] = $value;
} else {
$this->globals[$name] = $value;
}
}
If I remove the logical NOT operator from the comparison, then the method appears to work. But what am I breaking elsewhere? Can somebody look at this for the next build? Is it in fact a logic error?
I actually no longer think this is a logic error. I have been slammed at work and haven’t been able to investigate as much as I wish, but soon I think I can post with a definitive answer about using Globals with Slim’s TwigView.
Basically, you must instantiate an instance of Twig, then add the globals BEFORE adding to the container and adding TwigView middleware to the app. You have to add the globals, even if they’re initialized to NULL. So long as they’ve been added, you can change them later by using addGlobal(). That’s what the validator is checking in the code that I originally posted. If you’ve already started the middleware, but the global DOESN’T exist, then the exception is thrown.