2019-11-10 13:46:37 +00:00
|
|
|
<?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\Serializer\Normalizer;
|
|
|
|
|
|
|
|
use Symfony\Component\ErrorHandler\Exception\FlattenException;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Normalizes errors according to the API Problem spec (RFC 7807).
|
|
|
|
*
|
|
|
|
* @see https://tools.ietf.org/html/rfc7807
|
|
|
|
*
|
|
|
|
* @author Kévin Dunglas <dunglas@gmail.com>
|
|
|
|
* @author Yonel Ceruto <yonelceruto@gmail.com>
|
|
|
|
*/
|
|
|
|
class ProblemNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
|
|
|
|
{
|
|
|
|
private $debug;
|
|
|
|
private $defaultContext = [
|
|
|
|
'type' => 'https://tools.ietf.org/html/rfc2616#section-10',
|
|
|
|
'title' => 'An error occurred',
|
|
|
|
];
|
|
|
|
|
|
|
|
public function __construct(bool $debug = false, array $defaultContext = [])
|
|
|
|
{
|
|
|
|
$this->debug = $debug;
|
|
|
|
$this->defaultContext = $defaultContext + $this->defaultContext;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
2020-11-25 11:55:08 +00:00
|
|
|
*
|
|
|
|
* @return array
|
2019-11-10 13:46:37 +00:00
|
|
|
*/
|
|
|
|
public function normalize($exception, $format = null, array $context = [])
|
|
|
|
{
|
|
|
|
$context += $this->defaultContext;
|
2019-12-09 20:51:18 +00:00
|
|
|
$debug = $this->debug && ($context['debug'] ?? true);
|
2019-11-10 13:46:37 +00:00
|
|
|
|
|
|
|
$data = [
|
|
|
|
'type' => $context['type'],
|
|
|
|
'title' => $context['title'],
|
|
|
|
'status' => $context['status'] ?? $exception->getStatusCode(),
|
2019-11-26 00:08:07 +00:00
|
|
|
'detail' => $debug ? $exception->getMessage() : $exception->getStatusText(),
|
2019-11-10 13:46:37 +00:00
|
|
|
];
|
2019-11-26 00:08:07 +00:00
|
|
|
if ($debug) {
|
2019-11-10 13:46:37 +00:00
|
|
|
$data['class'] = $exception->getClass();
|
|
|
|
$data['trace'] = $exception->getTrace();
|
|
|
|
}
|
|
|
|
|
|
|
|
return $data;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function supportsNormalization($data, $format = null): bool
|
|
|
|
{
|
|
|
|
return $data instanceof FlattenException;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function hasCacheableSupportsMethod(): bool
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|