Completed
Push — develop ( 416857...9d3653 )
by Alejandro
17s queued 12s
created

BackwardsCompatibleProblemDetailsMiddleware   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 43
ccs 18
cts 18
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isVersionOne() 0 4 2
A __construct() 0 3 1
A process() 0 15 4
A makePayloadBackwardsCompatible() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Rest\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Throwable;
12
use Zend\Diactoros\Response\JsonResponse;
13
14
use function Functional\reduce_left;
15
use function Shlinkio\Shlink\Common\json_decode;
16
use function strpos;
17
18
/** @deprecated */
19
class BackwardsCompatibleProblemDetailsMiddleware implements MiddlewareInterface
20
{
21
    private const BACKWARDS_COMPATIBLE_FIELDS = [
22
        'error' => 'type',
23
        'message' => 'detail',
24
    ];
25
26
    private int $jsonFlags;
27
28 5
    public function __construct(int $jsonFlags)
29
    {
30 5
        $this->jsonFlags = $jsonFlags;
31
    }
32
33 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
34
    {
35 5
        $resp = $handler->handle($request);
36 5
        if ($resp->getHeaderLine('Content-type') !== 'application/problem+json' || ! $this->isVersionOne($request)) {
37 2
            return $resp;
38
        }
39
40
        try {
41 3
            $body = (string) $resp->getBody();
42 3
            $payload = $this->makePayloadBackwardsCompatible(json_decode($body));
43 1
        } catch (Throwable $e) {
44 1
            return $resp;
45
        }
46
47 2
        return new JsonResponse($payload, $resp->getStatusCode(), $resp->getHeaders(), $this->jsonFlags);
48
    }
49
50 4
    private function isVersionOne(ServerRequestInterface $request): bool
51
    {
52 4
        $path = $request->getUri()->getPath();
53 4
        return strpos($path, '/v') === false || strpos($path, '/v1') === 0;
54
    }
55
56 2
    private function makePayloadBackwardsCompatible(array $payload): array
57
    {
58
        return reduce_left(self::BACKWARDS_COMPATIBLE_FIELDS, function (string $newKey, string $oldKey, $c, $acc) {
59 2
            $acc[$oldKey] = $acc[$newKey];
60 2
            return $acc;
61 2
        }, $payload);
62
    }
63
}
64