• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

odan / Slim / 15356138503

30 May 2025 09:29PM UTC coverage: 98.372% (-0.2%) from 98.61%
15356138503

push

github

odan
Optimize JsonBodyParserMiddleware

1 of 1 new or added line in 1 file covered. (100.0%)

3 existing lines in 3 files now uncovered.

1027 of 1044 relevant lines covered (98.37%)

42.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.33
/Slim/Middleware/JsonBodyParserMiddleware.php
1
<?php
2

3
/**
4
 * Slim Framework (https://slimframework.com)
5
 *
6
 * @license https://github.com/slimphp/Slim/blob/5.x/LICENSE.md (MIT License)
7
 */
8

9
declare(strict_types=1);
10

11
namespace Slim\Middleware;
12

13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
use Psr\Http\Server\MiddlewareInterface;
16
use Psr\Http\Server\RequestHandlerInterface;
17
use RuntimeException;
18

19
final class JsonBodyParserMiddleware implements MiddlewareInterface
20
{
21
    private int $flags;
22

23
    public function __construct(int $flags = 0)
24
    {
25
        $this->flags = $flags;
14✔
26
    }
27

28
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
29
    {
30
        $method = $request->getMethod();
14✔
31
        $contentType = $request->getHeaderLine('Content-Type');
14✔
32

33
        if (!in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
14✔
UNCOV
34
            return $handler->handle($request);
×
35
        }
36

37
        if ($this->isJsonMediaType($contentType)) {
14✔
38
            $body = (string)$request->getBody();
10✔
39
            $parsed = json_decode($body, true, 512, $this->flags);
10✔
40

41
            if (json_last_error() !== JSON_ERROR_NONE) {
10✔
42
                throw new RuntimeException(sprintf('Invalid JSON body: %s', json_last_error_msg()));
2✔
43
            }
44

45
            if (is_array($parsed)) {
8✔
46
                $request = $request->withParsedBody($parsed);
5✔
47
            }
48
        }
49

50
        return $handler->handle($request);
12✔
51
    }
52

53
    /**
54
     * Check whether the content type is JSON or has a +json structured suffix.
55
     */
56
    private function isJsonMediaType(string $contentType): bool
57
    {
58
        $contentType = strtolower(trim(explode(';', $contentType)[0]));
14✔
59

60
        return $contentType === 'application/json' || str_ends_with($contentType, '+json');
14✔
61
    }
62
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc