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 3aeb146
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 2 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
91 changes: 90 additions & 1 deletion tests/ContentTypeMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,17 @@
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SplFileObject;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Diactoros\ServerRequest;
use function array_keys;
use function array_map;
use function assert;
use function ini_set;
use function is_string;
use function str_replace;
use function trim;

/**
* @coversDefaultClass \Lcobucci\ContentNegotiation\ContentTypeMiddleware
Expand Down Expand Up @@ -99,6 +106,50 @@ 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(
new UnformattedResponse(
new Response(),
new PersonDto(1, 'Testing'),
['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 Down Expand Up @@ -223,9 +274,47 @@ 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' => $this->createNaiveTemplatingEngine(),
],
['application/json' => new Formatter\Json()],
$streamFactory
);
}

private function createNaiveTemplatingEngine(): Formatter
{
return new class implements Formatter
{
/**
* {@inheritdoc}
*/
public function format($content, array $attributes = []): string
{
$template = $attributes['template'] ?? '';
assert(is_string($template));

$file = new SplFileObject(
__DIR__ . '/templates/naive/' . $template . '.html'
);

$data = (array) $content;

$variables = array_map(
function (string $attribute): string {
return '{' . $attribute . '}';
},
array_keys($data)
);

return trim(str_replace($variables, $data, $file->fread($file->getSize())));
}
};
}
}
8 changes: 8 additions & 0 deletions tests/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 3aeb146

Please sign in to comment.