Completed
Pull Request — master (#213)
by Alejandro
04:40
created

process()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 2
dl 0
loc 26
ccs 15
cts 15
cp 1
crap 4
rs 9.504
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Middleware\ShortUrl;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use Zend\Diactoros\Response;
11
use Zend\Diactoros\Response\JsonResponse;
12
13
class CreateShortUrlContentNegotiationMiddleware implements MiddlewareInterface
14
{
15
    private const PLAIN_TEXT = 'text';
16
    private const JSON = 'json';
17
18
    /**
19
     * Process an incoming server request and return a response, optionally delegating
20
     * response creation to a handler.
21
     * @throws \RuntimeException
22
     * @throws \InvalidArgumentException
23
     */
24 12
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
25
    {
26 12
        $response = $handler->handle($request);
27
28
        // If the response is not JSON, return it as is
29 12
        if (! $response instanceof JsonResponse) {
0 ignored issues
show
Bug introduced by
The class Zend\Diactoros\Response\JsonResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
30 1
            return $response;
31
        }
32
33 11
        $query = $request->getQueryParams();
34 11
        $acceptedType = isset($query['format'])
35 7
            ? $this->determineAcceptTypeFromQuery($query)
36 11
            : $this->determineAcceptTypeFromHeader($request->getHeaderLine('Accept'));
37
38
        // If JSON was requested, return the response from next handler as is
39 11
        if ($acceptedType === self::JSON) {
40 5
            return $response;
41
        }
42
43
        // If requested, return a plain text response containing the short URL only
44 6
        $resp = (new Response())->withHeader('Content-Type', 'text/plain');
45 6
        $body = $resp->getBody();
46 6
        $body->write($this->determineBody($response));
47 6
        $body->rewind();
48 6
        return $resp;
49
    }
50
51 7
    private function determineAcceptTypeFromQuery(array $query): string
52
    {
53 7
        if (! isset($query['format'])) {
54
            return self::JSON;
55
        }
56
57 7
        $format = \strtolower((string) $query['format']);
58 7
        return $format === 'txt' ? self::PLAIN_TEXT : self::JSON;
59
    }
60
61 4
    private function determineAcceptTypeFromHeader(string $acceptValue): string
62
    {
63 4
        $accepts = \explode(',', $acceptValue);
64 4
        $accept = \strtolower(\array_shift($accepts));
65 4
        return \strpos($accept, 'text/plain') !== false ? self::PLAIN_TEXT : self::JSON;
66
    }
67
68 6
    private function determineBody(JsonResponse $resp): string
69
    {
70 6
        $payload = $resp->getPayload();
71 6
        return $payload['shortUrl'] ?? $payload['error'] ?? '';
72
    }
73
}
74