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

slimphp / Slim / 15373855125

01 Jun 2025 10:15AM UTC coverage: 98.808% (+0.1%) from 98.663%
15373855125

Pull #3396

github

web-flow
Merge b22b0d19d into 89b8de367
Pull Request #3396: Add v5

124 of 128 new or added lines in 9 files covered. (96.88%)

995 of 1007 relevant lines covered (98.81%)

37.31 hits per line

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

86.67
/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 Slim\Exception\HttpBadRequestException;
18

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

23
    public function __construct(int $jsonFlags = JSON_THROW_ON_ERROR)
24
    {
25
        $this->flags = $jsonFlags;
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✔
NEW
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) {
8✔
NEW
42
                throw new HttpBadRequestException($request, sprintf('Invalid JSON body: %s', json_last_error_msg()));
×
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