Passed
Push — main ( 46cb87...b800f4 )
by Marc
18:17 queued 13:49
created

admin_process_get_request()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 11
rs 10
1
<?php declare(strict_types=1);
2
3
use html_go\exceptions\InternalException;
4
use html_go\model\Config;
5
6
/**
7
 * Main entry point for admin console requests.  This is call from there <code>route(...)</code>
8
 * function in the 'core/dispatcher.php' file.
9
 * @param string $method
10
 * @param string $uri
11
 * @throws InternalException If the HTTP Method is not supported.
12
 * @return \stdClass|NULL
13
 */
14
function admin_route(string $method, string $uri): ?\stdClass {
15
    $routes = require_once __DIR__.DS.'routes.php';
16
17
    if (isset($routes[$method])) {
18
        $content = admin_get_content_object($method, $uri, $routes);
19
    } else {
20
       throw new InternalException("Unsupported HTTP Method [$method]");
21
    }
22
23
    return $content;
24
}
25
26
/**
27
 * Returns the content object for the given URI (if there is one), otherwise returns <code>null</code>.
28
 * @param string $method
29
 * @param string $uri
30
 * @param array<mixed> $routes
31
 * @throws InternalException
32
 * @return \stdClass|NULL
33
 */
34
function admin_get_content_object(string $method, string $uri, array $routes): ?\stdClass {
35
    $slug = \substr($uri, \strlen(get_config()->getString(Config::KEY_ADMIN_CONTEXT)));
36
    $slug = normalize_uri($slug);
37
38
    $content = null;
39
    switch ($method) {
40
        case HTTP_GET:
41
            if (\array_key_exists($slug, $routes[$method])) {
42
                $object = $routes[$method][$slug];
43
                $params = [];
44
                $id = get_query_parameter(ID_STR);
45
                if ($id !== null) {
46
                    $params[ID_STR] = $id;
47
                }
48
                $content = \call_user_func($object->cb, $params);
49
            }
50
            break;
51
        case HTTP_POST:
52
            if (\array_key_exists($slug, $routes[$method])) {
53
                $object = $routes[$method][$slug];
54
                if (($formData = \filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING)) === false) {
55
                    throw new InternalException("filter_input_array function failed!");
56
                }
57
                $formData[ADMIN_CONTEXT_STR] = get_config()->getString(Config::KEY_ADMIN_CONTEXT);
58
                $content = \call_user_func($object->cb, $formData);
59
            }
60
            break;
61
        default:
62
            throw new InternalException("Unsupported HTTP Method [$method]");
63
    }
64
    return $content;
65
}
66