Failed Conditions
Push — master ( de6a42...332cc0 )
by Florent
15:27
created

RequestBodyParser::parseJson()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 10
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 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 Psr\Http\Message\ServerRequestInterface;
17
use League\Uri\QueryParser;
18
19
class RequestBodyParser
20
{
21
    public static function parseJson(ServerRequestInterface $request): array
22
    {
23
        if (!$request->hasHeader('Content-Type') || !in_array('application/json', $request->getHeader('Content-Type'))) {
24
            throw new \InvalidArgumentException('Unsupported request body content type.');
25
        }
26
        if (is_array($request->getParsedBody()) && !empty($request->getParsedBody())) {
27
            return $request->getParsedBody();
28
        }
29
30
        $body = $request->getBody()->getContents();
31
        $json = json_decode($body, true);
32
33
        if (!is_array($json)) {
34
            throw new \InvalidArgumentException('Invalid body');
35
        }
36
37
        return $json;
38
    }
39
40
    public static function parseFormUrlEncoded(ServerRequestInterface $request): array
41
    {
42
        if (!$request->hasHeader('Content-Type') || !in_array('application/x-www-form-urlencoded', $request->getHeader('Content-Type'))) {
43
            throw new \InvalidArgumentException('Unsupported request body content type.');
44
        }
45
        if (is_array($request->getParsedBody()) && !empty($request->getParsedBody())) {
46
            return $request->getParsedBody();
47
        }
48
49
        $body = $request->getBody()->getContents();
50
51
        return (new QueryParser())->parse($body);
52
    }
53
}
54