germania-kg / twig-requesthandler
PSR-15 RequestHandler for rendering Twig templates
Requires
- php: ^7.2|^8.0
- psr/http-message: ^1.0
- psr/http-server-handler: ^1.0
- twig/twig: ^2.0|^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- php-coveralls/php-coveralls: ^2.0
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^9.0
- slim/psr7: ^1.2
This package is auto-updated.
Last update: 2024-11-11 14:47:43 UTC
README
Germania KG · RequestHandler for Twig
Installation
$ composer require germania-kg/twig-requesthandler
Setup
The constructor accepts a Twig Environment and PSR-17 ResponseFactory. This example uses Tobias Nyholm's nyholm/psr7 package: composer require nyholm/psr7
<?php use Germania\TwigRequestHandler\TwigRequestHandler; use Twig\Environment as Twig; use Nyholm\Psr7\Factory\Psr17Factory; // Dependencies $twig = new Twig( ... ); $psr17Factory = new Psr17Factory; // Instantiation $request_handler = new TwigRequestHandler($twig, $psr17Factory);
Usage
Have a ServerRequest at hand and configure it with a template attribute and a context attribute.
- The template attribute must be a string as required by Twig.
- The context attribute must be an array as required by Twig; Instances of ArrayObject will be converted.
N.B. Invalid variable types will lead to a RuntimeException at runtime on request handling, not during configuration!
<?php $request = $psr17Factory->createServerRequest('GET', 'http://tnyholm.se'); $request = $request ->withAttribute('template', 'website.twig') ->withAttribute('context', [ 'title' => 'The Website title', 'company' => 'ACME corp.' ]);
Now, the above RequestHandler can be used as normal:
$response = $request_handler->handle($request); echo $response->getBody()->__toString(); // s.th. like // "<title>The Website title · ACME corp.</title>"
Configuration
You can change these default settings:
$request_handler->setTwig($twig); $request_handler->setResponseFactory($another);
You can change these default settings
$request_handler->setTemplateAttributeName("template") ->setContextAttributeName("context") ->setResponseContentType("text/html") ->setResponseStatusCode(200);
… and the core components:
$request_handler->setTwig($twig) ->setResponseFactory($another);
Issues
Development
Grab and go using one of these:
$ git clone git@github.com:GermaniaKG/TwigRequestHandler.git $ gh repo clone GermaniaKG/TwigRequestHandler
Unit tests
Either copy phpunit.xml.dist
to phpunit.xml
and adapt to your needs, or leave as is. Run PhpUnit test or composer scripts like this:
$ composer test # or $ vendor/bin/phpunit