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

process()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 4
rs 9.9666
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