-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
76 lines (58 loc) · 1.9 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
const CONFIG_PATH = 'config/routing.yml';
$loadedDependencies = [];
$klein = new \Klein\Klein();
$routeConfig = Yaml::parse(file_get_contents(CONFIG_PATH));
foreach ($routeConfig['routes'] as $currentConfig) {
validateClass($currentConfig['class']);
validateMethod($currentConfig['class'], $currentConfig['function']);
$reflectionClass = new ReflectionClass($currentConfig['class']);
$reflectionMethod = $reflectionClass->getMethod($currentConfig['function']);
$klein->respond(
$currentConfig['method'],
$currentConfig['path'],
$reflectionMethod->getClosure(
$reflectionClass->newInstanceArgs(constructArguments($currentConfig['dependency'] ?? [], $loadedDependencies))
)
);
}
$klein->dispatch();
/**
* @param array $dependencies
* @param array $loadedDependencies
* @return array
*/
function constructArguments(array $dependencies, array &$loadedDependencies): array
{
$arguments = [];
foreach ($dependencies as $dependency) {
validateClass($dependency);
if (!isset($loadedDependencies[$dependency])) {
$loadedDependencies[$dependency] = new $dependency;
}
$arguments[] = $loadedDependencies[$dependency];
}
return $arguments;
}
/**
* @param string $className
*/
function validateClass(string $className): void
{
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Class %s does not exist!', $className));
}
}
/**
* @param string $className
* @param string $methodName
*/
function validateMethod(string $className, string $methodName): void
{
$class = (new ReflectionClass($className))->newInstanceWithoutConstructor();
if (!method_exists($class, $methodName)) {
throw new RuntimeException(sprintf('Method %s does not exist!', $methodName));
}
}