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

Use PSR-17 factories #19

Merged
merged 1 commit into from
Jun 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ jobs:
- mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{.disabled,}
- if [[ ! $(php -m | grep -si xdebug) ]]; then echo "xdebug required for mutation tests"; exit 1; fi
script:
- ./vendor/bin/infection --threads=$(nproc) --min-msi=97 --min-covered-msi=97
- ./vendor/bin/infection --threads=$(nproc) --min-msi=100 --min-covered-msi=100
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"php": "^7.3",
"ext-json": "^1.7",
"fig/http-message-util": "^1.1",
"psr/http-factory": "^1.0",
"psr/http-server-middleware": "^1.0"
},
"require-dev": {
Expand Down
31 changes: 12 additions & 19 deletions src/ContentTypeMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@
use Middlewares\ContentType;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Stream;
use function assert;
use function strpos;
use function substr;

Expand All @@ -23,7 +21,7 @@ final class ContentTypeMiddleware implements MiddlewareInterface
private $negotiator;

/**
* @var callable
* @var StreamFactoryInterface
*/
private $streamFactory;

Expand All @@ -38,7 +36,7 @@ final class ContentTypeMiddleware implements MiddlewareInterface
public function __construct(
MiddlewareInterface $negotiator,
array $formatters,
callable $streamFactory
StreamFactoryInterface $streamFactory
) {
$this->negotiator = $negotiator;
$this->formatters = $formatters;
Expand All @@ -52,14 +50,12 @@ public function __construct(
public static function fromRecommendedSettings(
array $formats,
array $formatters,
?callable $streamFactory = null
StreamFactoryInterface $streamFactory
): self {
return new self(
new ContentType($formats),
$formatters,
$streamFactory ?? static function (): StreamInterface {
return new Stream('php://temp', 'wb+');
}
$streamFactory
);
}

Expand Down Expand Up @@ -98,18 +94,15 @@ private function extractContentType(string $contentType): string
*/
private function formatResponse(UnformattedResponse $response, ?Formatter $formatter): ResponseInterface
{
$body = ($this->streamFactory)();
assert($body instanceof StreamInterface);

$response = $response->withBody($body);

if ($formatter === null) {
return $response->withStatus(StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
return $response->withBody($this->streamFactory->createStream())
->withStatus(StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
}

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

return $response;
return $response->withBody(
$this->streamFactory->createStream(
$formatter->format($response->getUnformattedContent(), $response->getAttributes())
)
);
}
}
63 changes: 3 additions & 60 deletions tests/ContentTypeMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@

namespace Lcobucci\ContentNegotiation\Tests;

use AssertionError;
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;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\StreamFactory;
use function array_map;
use function ini_set;

/**
* @coversDefaultClass \Lcobucci\ContentNegotiation\ContentTypeMiddleware
Expand Down Expand Up @@ -170,61 +168,6 @@ public function processShouldReturnAResponseWithFormattedContentEvenWithoutForci
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 processShouldRaiseExceptionWhenInvalidStreamWasCreatedInDevelopmentMode(): void
{
ini_set('assert.exception', '1');

$this->expectException(AssertionError::class);
$this->processWithInvalidStreamFactory();
}

/**
* @test
*
* @covers ::__construct()
* @covers ::fromRecommendedSettings()
* @covers ::process()
* @covers ::extractContentType()
* @covers ::formatResponse()
*
* @uses \Lcobucci\ContentNegotiation\UnformattedResponse
* @uses \Lcobucci\ContentNegotiation\Formatter\Json
*/
public function processShouldRaiseAWarningWhenInvalidStreamWasCreatedInDevelopmentMode(): void
{
ini_set('assert.exception', '0');

$this->expectException(Warning::class);
$this->processWithInvalidStreamFactory();
}

private function processWithInvalidStreamFactory(): void
{
$middleware = $this->createMiddleware(
true,
static function () {
return false;
}
);

$middleware->process(
new ServerRequest(),
$this->createRequestHandler($this->createResponse())
);
}

/**
* @param mixed[] $attributes
*/
Expand Down Expand Up @@ -261,15 +204,15 @@ public function handle(ServerRequestInterface $request): ResponseInterface
};
}

private function createMiddleware(bool $forceCharset = true, ?callable $streamFactory = null): ContentTypeMiddleware
private function createMiddleware(bool $forceCharset = true): ContentTypeMiddleware
{
return ContentTypeMiddleware::fromRecommendedSettings(
$this->configureCharset($forceCharset),
[
'application/json' => new Formatter\Json(),
'text/html' => new NaiveTemplateEngine(),
],
$streamFactory
new StreamFactory()
);
}

Expand Down