RequestBodyParser   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 11

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parseFormUrlEncoded() 0 13 5
A parseJson() 0 18 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\Core\Util;
15
16
use InvalidArgumentException;
17
use League\Uri\QueryParser;
18
use Psr\Http\Message\ServerRequestInterface;
19
20
class RequestBodyParser
21
{
22
    public static function parseJson(ServerRequestInterface $request): array
23
    {
24
        if (!$request->hasHeader('Content-Type') || !\in_array('application/json', $request->getHeader('Content-Type'), true)) {
25
            throw new InvalidArgumentException('Unsupported request body content type.');
26
        }
27
        $parsedBody = $request->getParsedBody();
28
        if (\is_array($parsedBody) && 0 !== \count($parsedBody)) {
29
            return $parsedBody;
30
        }
31
32
        $body = $request->getBody()->getContents();
33
        $json = \Safe\json_decode($body, true);
34
35
        if (!\is_array($json)) {
36
            throw new InvalidArgumentException('Invalid body');
37
        }
38
39
        return $json;
40
    }
41
42
    public static function parseFormUrlEncoded(ServerRequestInterface $request): array
43
    {
44
        if (!$request->hasHeader('Content-Type') || !\in_array('application/x-www-form-urlencoded', $request->getHeader('Content-Type'), true)) {
45
            throw new InvalidArgumentException('Unsupported request body content type.');
46
        }
47
        $parsedBody = $request->getParsedBody();
48
        if (\is_array($parsedBody) && 0 !== \count($parsedBody)) {
49
            return $parsedBody;
50
        }
51
52
        $body = $request->getBody()->getContents();
53
54
        return (new QueryParser())->parse($body, '&', QueryParser::RFC1738_ENCODING);
55
    }
56
}
57