slimphp / Twig-View

Slim Framework view helper built on top of the Twig templating component
http://slimframework.com
MIT License
359 stars 87 forks source link

TwigMiddleware::createFromContainer does not set request attribute "view" #322

Open odan opened 3 months ago

odan commented 3 months ago

The static method TwigMiddleware::createFromContainer() does not pass the $attributeName parameter to the constructor.

https://github.com/slimphp/Twig-View/blob/3.x/src/TwigMiddleware.php#L56-L60

Example application

<?php

use DI\Container;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

require __DIR__ . '/../vendor/autoload.php';

$container = new Container();
AppFactory::setContainer($container);

// Set view in Container
$container->set('view', function () {
    return Twig::create(__DIR__ . '/../templates', ['cache' => false]);
});

$app = AppFactory::create();

$app->add(TwigMiddleware::createFromContainer($app));
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);

$app->get('/', function (Request $request, Response $response) {
    $view = Twig::fromRequest($request); // throws RuntimeException here

    $response->getBody()->write($view->fetchFromString('Current_url: {{ current_url() }}'));

    return $response;
});

$app->run();

Result: Uncaught RuntimeException: Twig could not be found in the server request attributes using the key "view"

Slim Application Error
The application could not run because of the following error:

Details
Type: RuntimeException
Code: 0
Message: Twig could not be found in the server request attributes using the key "view".
File: vendor/slim/twig-view/src/Twig.php
Line: 74

https://github.com/slimphp/Twig-View/blob/3.x/src/Twig.php#L73-L77

Expected result: No error

Workaround: Use the create method instead:

$app->add(TwigMiddleware::create($app, $container->get('view')));

// or
$app->add(TwigMiddleware::create($app, $container->get(Twig:class)));

// or manually
$app->add(
    new TwigMiddleware(
        $container->get('view'),
        $app->getRouteCollector()->getRouteParser(),
        $app->getBasePath(),
        'view'  // <<<<---- see here
    )
);