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

Update the render method in the Twig class #235

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Expand Up @@ -106,6 +106,18 @@ $app->get('/hi/{name}', function ($request, $response, $args) {
// Run app
$app->run();
```
## Two ways to use the render() method

The first:
```php
$view->render($response, 'example.html', ['name' => 'Josh'])
````
The second requires you to set any implementation of the PSR-17 response factory otherwise an exception will be thrown:
```php
$view->setResponseFactory($someResponseFactory);

$view->render('example.html', ['name' => 'Josh'])
```

## Custom template functions

Expand Down
4 changes: 2 additions & 2 deletions composer.json
Expand Up @@ -20,14 +20,14 @@
"require": {
"php": "^7.3 || ^8.0",
"psr/http-message": "^1.0",
"psr/http-factory": "^1.0",
"slim/slim": "^4.9",
"twig/twig": "^3.3"
"twig/twig": "^3.3",
},
"require-dev": {
"phpunit/phpunit": "^9.3.8",
"phpspec/prophecy-phpunit": "^2.0",
"phpstan/phpstan": "^0.12.99",
"psr/http-factory": "^1.0",
"squizlabs/php_codesniffer": "^3.6"
},
"autoload": {
Expand Down
45 changes: 39 additions & 6 deletions src/Twig.php
Expand Up @@ -11,6 +11,8 @@

use ArrayAccess;
use ArrayIterator;
use InvalidArgumentException;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
Expand Down Expand Up @@ -55,6 +57,13 @@ class Twig implements ArrayAccess
*/
protected $defaultVariables = [];

/**
* PSR-17 response factory
*
* @var ResponseFactoryInterface
*/
protected $responseFactory;

/**
* @param ServerRequestInterface $request
* @param string $attributeName
Expand Down Expand Up @@ -129,6 +138,14 @@ public function addRuntimeLoader(RuntimeLoaderInterface $runtimeLoader): void
$this->environment->addRuntimeLoader($runtimeLoader);
}

/**
* @param ResponseFactoryInterface $responseFactory
*/
public function setResponseFactory(ResponseFactoryInterface $responseFactory): void
{
$this->responseFactory = $responseFactory;
}

/**
* Fetch rendered template
*
Expand Down Expand Up @@ -189,21 +206,37 @@ public function fetchFromString(string $string = '', array $data = []): string
/**
* Output rendered template
*
* @param ResponseInterface $response
* @param string $template Template pathname relative to templates directory
* @param array<string, mixed> $data Associative array of template variables
* @param ResponseInterface|string $responseOrTemplate Response or template pathname relative to templates dir.
* @param string|array<string, mixed> $templateOrData Template pathname or template variables
* @param array<string, mixed> $data Associative array of template variables
*
* @throws LoaderError When the template cannot be found
* @throws SyntaxError When an error occurred during compilation
* @throws RuntimeError When an error occurred during rendering
*
* @return ResponseInterface
*/
public function render(ResponseInterface $response, string $template, array $data = []): ResponseInterface
public function render($responseOrTemplate, $templateOrData = [], array $data = []): ResponseInterface
{
$response->getBody()->write($this->fetch($template, $data));
if ($responseOrTemplate instanceof ResponseInterface && is_string($templateOrData)) {
$responseOrTemplate->getBody()->write($this->fetch($templateOrData, $data));

return $response;
return $responseOrTemplate;
} elseif (is_string($responseOrTemplate) && is_array($templateOrData)) {
if (!isset($this->responseFactory)) {
throw new RuntimeException('Response factory is not defined');
}

$response = $this->responseFactory->createResponse();
$response->getBody()->write($this->fetch($responseOrTemplate, $templateOrData));

return $response;
} else {
throw new InvalidArgumentException(sprintf(
'Invalid arguments were passed to the %s method',
__METHOD__
));
}
}

/**
Expand Down
63 changes: 56 additions & 7 deletions tests/TwigTest.php
Expand Up @@ -14,11 +14,9 @@
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Slim\Views\Twig;
use Slim\Views\TwigContext;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\RuntimeExtensionInterface;
use Twig\Loader\ArrayLoader;
use Twig\Loader\FilesystemLoader;
use Twig\Loader\LoaderInterface;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

Expand Down Expand Up @@ -98,7 +96,7 @@ public function testAddRuntimeLoader()

// Mock a runtime loader.
$runtimeLoader = $this->getMockBuilder(RuntimeLoaderInterface::class)
->setMethods(['load'])
->onlyMethods(['load'])
->getMock();

// The method `load` should be called once and should return the mocked runtime extension.
Expand Down Expand Up @@ -267,11 +265,15 @@ public function testMultipleDirectoriesWithoutNamespaces()
$this->assertEquals("<p>Hi, my name is Peter and I am male.</p>\n", $multiDirectory);
}

public function testRender()
/**
* The auxiliary method for the testRender...() methods
*/
private function getViewAndMocksForRender(): array
{
$loader = new ArrayLoader([
'example.html' => "<p>Hi, my name is {{ name }}.</p>\n"
]);

$view = new Twig($loader);

$mockBody = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
Expand All @@ -291,12 +293,59 @@ public function testRender()
->method('getBody')
->willReturn($mockBody);

$response = $view->render($mockResponse, 'example.html', [
'name' => 'Josh'
]);
$mockResponseFactory = $this->getMockBuilder('Psr\Http\Message\ResponseFactoryInterface')
->disableOriginalConstructor()
->getMock();

return [$view, $mockResponse, $mockResponseFactory];
}

public function testRenderWithoutResponseFactory()
{
[$view, $mockResponse] = $this->getViewAndMocksForRender();

$response = $view->render($mockResponse, 'example.html', ['name' => 'Josh']);
$this->assertInstanceOf(ResponseInterface::class, $response);
}

public function testRenderWithResponseFactory()
{
[$view, $mockResponse, $mockResponseFactory] = $this->getViewAndMocksForRender();

$mockResponseFactory->expects($this->once())
->method('createResponse')
->willReturn($mockResponse);

$view->setResponseFactory($mockResponseFactory);

$response = $view->render('example.html', ['name' => 'Josh']);
$this->assertInstanceOf(ResponseInterface::class, $response);
}

public function testInvalidArgumentInRender()
{
$loader = new ArrayLoader([
'example.html' => "<p>Hi, my name is {{ name }}.</p>\n"
]);
$view = new Twig($loader);

$this->expectExceptionMessage('Invalid arguments were passed to the Slim\Views\Twig::render method');

$view->render('example.html', 'example.html');
}

public function testNotDefinedResponseFactoryInRender()
{
$loader = new ArrayLoader([
'example.html' => "<p>Hi, my name is {{ name }}.</p>\n"
]);
$view = new Twig($loader);

$this->expectExceptionMessage('Response factory is not defined');

$view->render('example.html', ['name' => 'Josh']);
}

public function testGetLoader()
{
$loader = $this->createMock(LoaderInterface::class);
Expand Down