germania-kg/twig-requesthandler

PSR-15 RequestHandler for rendering Twig templates

1.0.5 2021-02-11 06:52 UTC

This package is auto-updated.

Last update: 2024-04-11 13:38:09 UTC


README

68747470733a2f2f7374617469632e6765726d616e69612d6b672e636f6d2f6c6f676f732f67612d6c6f676f2d323031362d7765622e7376677a

Germania KG · RequestHandler for Twig

Packagist PHP version Build Status Scrutinizer Code Quality Code Coverage Build Status

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

See full issues list.

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