Completed
Pull Request — 1.x (#124)
by Akihito
02:34 queued 43s
created

WebRouter::getUnsafeQuery()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 5
nop 3
dl 0
loc 24
ccs 0
cts 0
cp 0
crap 42
rs 9.1111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Sunday\Provide\Router;
6
7
use BEAR\Resource\Exception\BadRequestException;
8
use BEAR\Sunday\Annotation\DefaultSchemeHost;
9
use BEAR\Sunday\Extension\Router\RouterInterface;
10
use BEAR\Sunday\Extension\Router\RouterMatch;
11
use function is_array;
12
13
final class WebRouter implements RouterInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $schemeHost;
19
20
    /**
21 5
     * @DefaultSchemeHost
22
     */
23 5
    public function __construct(string $schemeHost)
24 5
    {
25
        $this->schemeHost = $schemeHost;
26
    }
27
28
    /**
29 2
     * {@inheritdoc}
30
     */
31 2
    public function match(array $globals, array $server)
32 2
    {
33 2
        $method = \strtolower($server['REQUEST_METHOD']);
34 2
        $match = new RouterMatch;
35 2
        $match->method = $method;
36 2
        $match->path = $this->schemeHost . \parse_url($server['REQUEST_URI'], PHP_URL_PATH);
37
        $match->query = ($method === 'get') ? $globals['_GET'] : $this->getUnsafeQuery($method, $server, $globals);
38
39 2
        return $match;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 1
    public function generate($name, $data)
46
    {
47 1
        return $name;
48
    }
49
50
    /**
51
     * Return request query by media-type
52
     */
53
    private function getUnsafeQuery(string $method, array $globals, array $server) : array
54
    {
55
        if ($method === 'post' && is_array($globals['_POST'])) {
56
            return $globals['_POST'];
57
        }
58
        $contentType = $server['CONTENT_TYPE'] ?? ($server['HTTP_CONTENT_TYPE']) ?? '';
59
        $isFormUrlEncoded = strpos($contentType, 'application/x-www-form-urlencoded') !== false;
60
        $rawBody = $server['HTTP_RAW_POST_DATA'] ?? rtrim((string) file_get_contents('php://input'));
61
        if ($isFormUrlEncoded) {
62
            \parse_str(rtrim($rawBody), $put);
63
64
            return $put;
65
        }
66
        $isApplicationJson = strpos($contentType, 'application/json') !== false;
67
        if (! $isApplicationJson) {
68
            return [];
69
        }
70
        $content = json_decode($rawBody, true);
71
        $error = json_last_error();
72
        if ($error !== JSON_ERROR_NONE) {
73
            throw new BadRequestException(json_last_error_msg());
74
        }
75
76
        return $content;
77
    }
78
}
79