/
Executor.php
75 lines (65 loc) · 2.11 KB
/
Executor.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
<?php
namespace Pux;
use Exception;
use LogicException;
use ReflectionClass;
use ReflectionObject;
use ReflectionParameter;
class Executor
{
/**
* Execute the matched route
*
* $route: {pcre flag}, {pattern}, {callback}, {options}
*
* @return string the response
*/
public static function execute(array $route)
{
list($pcre, $pattern, $cb, $options) = $route;
// create the reflection class
$rc = new ReflectionClass( $cb[0] );
$constructArgs = null;
if (isset($options['constructor_args'])) {
$constructArgs = $options['constructor_args'];
}
// if the first argument is a class name string,
// then create the controller object.
if (is_string($cb[0])) {
$cb[0] = $controller = $constructArgs ? $rc->newInstanceArgs($constructArgs) : $rc->newInstance();
} else {
$controller = $cb[0];
}
// check controller action method
if ($controller && ! method_exists( $controller ,$cb[1])) {
throw new LogicException("Controller action method '{$cb[1]}' doesn't exist.");
/*
throw new Exception('Method ' .
get_class($controller) . "->{$cb[1]} does not exist.", $route );
*/
}
$rps = $rc->getMethod($cb[1])->getParameters();
// XXX:
$vars = isset($options['vars'])
? $options['vars']
: array()
;
$arguments = array();
foreach ($rps as $param) {
$n = $param->getName();
if (isset( $vars[ $n ] ))
{
$arguments[] = $vars[ $n ];
}
else if (isset($route[3]['default'][ $n ] )
&& $default = $route[3]['default'][ $n ] )
{
$arguments[] = $default;
}
else if ( ! $param->isOptional() && ! $param->allowsNull() ) {
throw new Exception('parameter is not defined.');
}
}
return call_user_func_array($cb, $arguments);
}
}