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 16 commits into
base: 7.4
Choose a base branch
from
Open
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
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 UnexpectedValueException
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?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(
int $status = 500,
string $type = 'about:blank',
?string $title = null,
?string $detail = null,
?string $instance = null,
?array $extensions = [],
) {
parent::__construct();

$this->statusCode = $status;

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

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

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

$problemDetails = [
'type' => $type,
'title' => $title,
'detail' => $detail,
'status' => $status,
'instance' => $instance,
...$extensions,
];

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

$this->headers->set('Content-Type', 'application/problem+json');

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

$this->setContent($content);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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;

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

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

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

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

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

$this->assertSame(401, json_decode($problemDetails->getContent(), true)['status']);
$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(500, extensions: ['foo' => 'bar']);

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

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

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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy