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

Add support for streamed response #174

Merged
merged 1 commit into from
Jan 28, 2024
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
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