Skip to content

Commit

Permalink
Add support for streamed response (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
bastien-phi authored Jan 28, 2024
1 parent 73f96b4 commit 46d8268
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Validation/ResponseValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Opis\JsonSchema\Validator;
use Spectator\Exceptions\ResponseValidationException;
use Spectator\Exceptions\SchemaValidationException;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ResponseValidator extends AbstractValidator
{
Expand Down Expand Up @@ -163,7 +164,7 @@ protected function schemaType(Schema $schema)
*/
protected function body($contentType, $schemaType)
{
$body = $this->response->getContent();
$body = $this->response instanceof StreamedResponse ? $this->streamedContent() : $this->response->getContent();

if (in_array($schemaType, ['object', 'array', 'allOf', 'anyOf', 'oneOf'], true)) {
if (in_array($contentType, ['application/json', 'application/vnd.api+json', 'application/problem+json'])) {
Expand All @@ -176,6 +177,23 @@ protected function body($contentType, $schemaType)
return $body;
}

protected function streamedContent(): string
{
$content = '';

ob_start(function (string $buffer) use (&$content): string {
$content .= $buffer;

return '';
});

$this->response->sendContent();

ob_end_clean();

return $content;
}

/**
* @return string
*/
Expand Down
19 changes: 19 additions & 0 deletions tests/ResponseValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,25 @@ public function test_validates_invalid_json_response(): void
->assertValidationMessage('All array items must match schema');
}

public function test_validates_valid_streamed_json_response(): void
{
Route::get('/users', static function () {
return response()->stream(function () {
echo json_encode([
[
'id' => 1,
'name' => 'Jim',
'email' => '[email protected]',
],
]);
}, 200, ['Content-Type' => 'application/json']);
})->middleware(Middleware::class);

$this->getJson('/users')
->assertValidRequest()
->assertValidResponse();
}

public function test_validates_valid_problem_json_response()
{
Route::get('/users', function () {
Expand Down

0 comments on commit 46d8268

Please sign in to comment.