Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
odan opened this issue Jul 16, 2024 · 0 comments
Open
Labels

Comments

@odan
Copy link
Contributor

odan commented Jul 16, 2024

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
    )
);
@odan odan added the bug label Jul 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant