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

WebRouter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 64
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 3 1
A getUnsafeQuery() 0 24 6
A __construct() 0 3 1
A match() 0 9 2
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