Skip to content

Commit

Permalink
Make middleware pass the response attributes to formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
lcobucci committed Apr 22, 2018
1 parent f79c665 commit 1587b6b
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/ContentTypeMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private function formatResponse(UnformattedResponse $response, ?Formatter $forma
return $response->withStatus(StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
}

$body->write($formatter->format($response->getUnformattedContent()));
$body->write($formatter->format($response->getUnformattedContent(), $response->getAttributes()));
$body->rewind();

return $response;
Expand Down
77 changes: 64 additions & 13 deletions tests/ContentTypeMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Fig\Http\Message\StatusCodeInterface;
use Lcobucci\ContentNegotiation\ContentTypeMiddleware;
use Lcobucci\ContentNegotiation\Formatter;
use Lcobucci\ContentNegotiation\Tests\Formatter\NaiveTemplateEngine;
use Lcobucci\ContentNegotiation\UnformattedResponse;
use PHPUnit\Framework\Error\Warning;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -60,9 +61,7 @@ public function processShouldReturnAResponseWithErrorWhenFormatterWasNotFound():

$response = $middleware->process(
(new ServerRequest())->withAddedHeader('Accept', 'text/plain'),
$this->createRequestHandler(
new UnformattedResponse(new Response(), new PersonDto(1, 'Testing'))
)
$this->createRequestHandler($this->createResponse())
);

self::assertInstanceOf(UnformattedResponse::class, $response);
Expand All @@ -88,9 +87,7 @@ public function processShouldReturnAResponseWithFormattedContent(): void

$response = $middleware->process(
new ServerRequest(),
$this->createRequestHandler(
new UnformattedResponse(new Response(), new PersonDto(1, 'Testing'))
)
$this->createRequestHandler($this->createResponse())
);

self::assertInstanceOf(UnformattedResponse::class, $response);
Expand All @@ -99,6 +96,44 @@ public function processShouldReturnAResponseWithFormattedContent(): void
self::assertJsonStringEqualsJsonString('{"id":1,"name":"Testing"}', (string) $response->getBody());
}

/**
* @test
*
* @covers ::__construct()
* @covers ::fromRecommendedSettings()
* @covers ::process()
* @covers ::extractContentType()
* @covers ::formatResponse()
*
* @uses \Lcobucci\ContentNegotiation\UnformattedResponse
* @uses \Lcobucci\ContentNegotiation\Formatter\Json
*/
public function processShouldPassAttributesToTheFormatterProperly(): void
{
$middleware = $this->createMiddleware();

$response = $middleware->process(
(new ServerRequest())->withAddedHeader('Accept', 'text/html'),
$this->createRequestHandler($this->createResponse(['template' => 'person']))
);

$formattedContent = <<<'TEMPLATE'
<section>
<dl>
<dt>Identifier</dt>
<dd>1</dd>
<dt>Name</dt>
<dd>Testing</dd>
</dl>
</section>
TEMPLATE;

self::assertInstanceOf(UnformattedResponse::class, $response);
self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
self::assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
self::assertSame($formattedContent, (string) $response->getBody());
}

/**
* @test
*
Expand All @@ -117,9 +152,7 @@ public function processShouldReturnAResponseWithFormattedContentEvenWithoutForci

$response = $middleware->process(
new ServerRequest(),
$this->createRequestHandler(
new UnformattedResponse(new Response(), new PersonDto(1, 'Testing'))
)
$this->createRequestHandler($this->createResponse())
);

self::assertInstanceOf(UnformattedResponse::class, $response);
Expand Down Expand Up @@ -179,9 +212,19 @@ function () {

$middleware->process(
new ServerRequest(),
$this->createRequestHandler(
new UnformattedResponse(new Response(), new PersonDto(1, 'Testing'))
)
$this->createRequestHandler($this->createResponse())
);
}

/**
* @param mixed[] $attributes
*/
private function createResponse(array $attributes = []): UnformattedResponse
{
return new UnformattedResponse(
new Response(),
new PersonDto(1, 'Testing'),
$attributes
);
}

Expand Down Expand Up @@ -223,8 +266,16 @@ private function createMiddleware(bool $forceCharset = true, ?callable $streamFa
'mime-type' => ['text/plain'],
'charset' => $forceCharset,
],
'html' => [
'extension' => ['html', 'htm'],
'mime-type' => ['text/html', 'application/xhtml+xml'],
'charset' => $forceCharset,
],
],
[
'application/json' => new Formatter\Json(),
'text/html' => new NaiveTemplateEngine(),
],
['application/json' => new Formatter\Json()],
$streamFactory
);
}
Expand Down
57 changes: 57 additions & 0 deletions tests/Formatter/NaiveTemplateEngine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);

namespace Lcobucci\ContentNegotiation\Tests\Formatter;

use Lcobucci\ContentNegotiation\Formatter;
use SplFileObject;
use function array_keys;
use function array_map;
use function assert;
use function is_string;
use function str_replace;
use function trim;

final class NaiveTemplateEngine implements Formatter
{
private const BASE_DIR = __DIR__ . '/templates/naive/';
private const EXTENSION = 'html';

/**
* {@inheritdoc}
*/
public function format($content, array $attributes = []): string
{
$template = $this->getTemplateContent($attributes);

return $this->render($template, (array) $content);
}

/**
* @param mixed[] $attributes
*/
private function getTemplateContent(array $attributes): string
{
$template = $attributes['template'] ?? '';
assert(is_string($template));

$file = new SplFileObject(self::BASE_DIR . $template . '.' . self::EXTENSION);

return $file->fread($file->getSize());
}

/**
* @param mixed[] $data
*/
private function render(string $template, array $data): string
{
$variables = array_map(
function (string $attribute): string {
return '{' . $attribute . '}';
},
array_keys($data)
);

return trim(str_replace($variables, $data, $template));
}
}
8 changes: 8 additions & 0 deletions tests/Formatter/templates/naive/person.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<section>
<dl>
<dt>Identifier</dt>
<dd>{id}</dd>
<dt>Name</dt>
<dd>{name}</dd>
</dl>
</section>

0 comments on commit 1587b6b

Please sign in to comment.