Updated to problem-details 1.1, removing custom code

This commit is contained in:
Alejandro Celaya
2019-12-30 22:42:29 +01:00
parent 416857e129
commit bd6243b2ac
5 changed files with 21 additions and 64 deletions

View File

@@ -15,6 +15,7 @@ use function Functional\reduce_left;
use function Shlinkio\Shlink\Common\json_decode;
use function strpos;
/** @deprecated */
class BackwardsCompatibleProblemDetailsMiddleware implements MiddlewareInterface
{
private const BACKWARDS_COMPATIBLE_FIELDS = [
@@ -22,56 +23,36 @@ class BackwardsCompatibleProblemDetailsMiddleware implements MiddlewareInterface
'message' => 'detail',
];
private array $defaultTypeFallbacks;
private int $jsonFlags;
public function __construct(array $defaultTypeFallbacks, int $jsonFlags)
public function __construct(int $jsonFlags)
{
$this->defaultTypeFallbacks = $defaultTypeFallbacks;
$this->jsonFlags = $jsonFlags;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$resp = $handler->handle($request);
if ($resp->getHeaderLine('Content-type') !== 'application/problem+json') {
if ($resp->getHeaderLine('Content-type') !== 'application/problem+json' || ! $this->isVersionOne($request)) {
return $resp;
}
try {
$body = (string) $resp->getBody();
$payload = json_decode($body);
$payload = $this->makePayloadBackwardsCompatible(json_decode($body));
} catch (Throwable $e) {
return $resp;
}
$payload = $this->mapStandardErrorTypes($payload, $resp->getStatusCode());
if ($this->isVersionOne($request)) {
$payload = $this->makePayloadBackwardsCompatible($payload);
}
return new JsonResponse($payload, $resp->getStatusCode(), $resp->getHeaders(), $this->jsonFlags);
}
private function mapStandardErrorTypes(array $payload, int $respStatusCode): array
{
$type = $payload['type'] ?? '';
if (strpos($type, 'https://httpstatus.es') === 0) {
$payload['type'] = $this->defaultTypeFallbacks[$respStatusCode] ?? $type;
}
return $payload;
}
/** @deprecated When Shlink 2 is released, do not chekc the version */
private function isVersionOne(ServerRequestInterface $request): bool
{
$path = $request->getUri()->getPath();
return strpos($path, '/v') === false || strpos($path, '/v1') === 0;
}
/** @deprecated When Shlink v2 is released, do not map old fields */
private function makePayloadBackwardsCompatible(array $payload): array
{
return reduce_left(self::BACKWARDS_COMPATIBLE_FIELDS, function (string $newKey, string $oldKey, $c, $acc) {