Skip to content

[HttpFoundation] Add ProblemDetailsJsonResponse for HTTP APIs #61208

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

Open
wants to merge 10 commits into
base: 7.4
Choose a base branch
from
Open
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Deprecate using `Request::sendHeaders()` after headers have already been sent; use a `StreamedResponse` instead
* Add `ProblemDetailsJsonResponse` to return a JSON representation of a problem encountered in an HTTP API

7.3
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpFoundation\Exception;

/**
* @author Abdellah Ramadan <ramadanabdel24@gmail.com>
*/
class ProblemDetailsJsonResponseException extends \Exception
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpFoundation;

use Symfony\Component\HttpFoundation\Exception\ProblemDetailsJsonResponseException;

/**
* Represents a JSON response with a Problem Details object.
*
* @author Abdellah Ramadan <ramadanabdel24@gmail.com>
*/
class ProblemDetailsJsonResponse extends Response
{
public function __construct(
protected ?int $status = null,
protected ?string $title = null,
protected ?string $type = null,
protected ?string $detail = null,
protected ?string $instance = null,
protected ?array $extensions = [],
) {
parent::__construct();

if ($this->title && null === $this->type) {
$this->title = Response::$statusTexts[$this->status];
}

if (null === $this->title && null === $this->detail) {
$this->title = Response::$statusTexts[$this->status];
}

$this->setProblemContent();
}

private function setHeaders(): void
{
$this->headers->set('Content-Type', 'application/problem+json');
}

/**
* @throws ProblemDetailsJsonResponseException
*/
private function checkStatusCode(): void
{
if ($this->status < 400 || $this->status > 599) {
throw new ProblemDetailsJsonResponseException(\sprintf('The status code "%s" is not a valid HTTP Status Code error.', $this->statusCode));
}
}

private function setStatus(): void
{
$this->status = $this->status ?? 520;
$this->statusCode = $this->status;
}

/**
* @throws ProblemDetailsJsonResponseException
* @throws \JsonException
*/
protected function setProblemContent(): string
{
$this->setStatus();
$this->checkStatusCode();
$this->setHeaders();

if (null !== $this->type) {
$scheme = parse_url($this->type, \PHP_URL_SCHEME);
if (null === $scheme) {
throw new ProblemDetailsJsonResponseException("Invalid url type: $this->type.");
}
}

$problemDetails = [
'type' => $this->type ?? 'about:blank',
'title' => $this->title ?? Response::$statusTexts[$this->statusCode] ?? 'Unknown Error',
'detail' => $this->detail,
'status' => $this->status,
'instance' => $this->instance,
...$this->extensions,
];

$problemDetails = array_filter($problemDetails, function ($value) {
return null !== $value;
});

$content = json_encode($problemDetails, \JSON_FORCE_OBJECT | \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR);

return $this->setContent($content);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/

namespace Symfony\Component\HttpFoundation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\ProblemDetailsJsonResponse;

/**
* Problem Detail Response Tests.
*
* @author Abdellah Ramadan <ramadanabdel24@gmail.com>
*/
class ProblemDetailsJsonResponseTest extends TestCase
{
public function testNewProblemWithNoParams()
{
$problemDetails = new ProblemDetailsJsonResponse();
$this->assertEquals(520, $problemDetails->getStatusCode());

$this->assertSame('about:blank', json_decode($problemDetails->getContent(), true)['type']);

$this->assertSame('application/problem+json', $problemDetails->headers->get('Content-Type'));
$this->assertSame('Unknown Error', json_decode($problemDetails->getContent(), true)['title']);
}

public function testStatusCode()
{
$problemDetails = new ProblemDetailsJsonResponse(404);
$this->assertEquals(404, $problemDetails->getStatusCode());
}

public function testNewProblemWithParams()
{
$problemDetails = new ProblemDetailsJsonResponse(401, 'Unauthorized', 'https://example.com/not-found-docs', 'No access to this resource');

$this->assertEquals(401, $problemDetails->getStatusCode());
$this->assertSame('Unauthorized', json_decode($problemDetails->getContent(), true)['title']);
$this->assertSame('No access to this resource', json_decode($problemDetails->getContent(), true)['detail']);
$this->assertSame('https://example.com/not-found-docs', json_decode($problemDetails->getContent(), true)['type']);
$this->assertSame('application/problem+json', $problemDetails->headers->get('Content-Type'));
}

public function testEmptyTitle()
{
$problemDetails = new ProblemDetailsJsonResponse(402);
$this->assertNotNull(json_decode($problemDetails->getContent(), true)['title']);
$this->assertSame('Payment Required', json_decode($problemDetails->getContent(), true)['title']);
}

public function testExtensions()
{
$problemDetails = new ProblemDetailsJsonResponse(extensions: ['foo' => 'bar']);

$this->assertArrayHasKey('foo', json_decode($problemDetails->getContent(), true));

$problemDetails = new ProblemDetailsJsonResponse(extensions: ['foo' => 'bar', 'baz' => ['bar' => 'foo']]);
$this->assertIsArray(json_decode($problemDetails->getContent(), true)['baz']);
}

public function testInstance()
{
$problemDetails = new ProblemDetailsJsonResponse(instance: 'article/5');
$this->assertIsString(json_decode($problemDetails->getContent(), true)['instance']);
}
}
Loading