|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the jade/jade package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Slince <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Jade\HttpKernel; |
|
13
|
|
|
|
|
14
|
|
|
use Jade\ContainerAwareInterface; |
|
15
|
|
|
use Jade\ContainerInterface; |
|
16
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
17
|
|
|
|
|
18
|
|
|
class ControllerResolver implements ControllerResolverInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var ContainerInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $container; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(ContainerInterface $container) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->container = $container; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* {@inheritdoc} |
|
32
|
|
|
*/ |
|
33
|
|
|
public function getController(ServerRequestInterface $request) |
|
34
|
|
|
{ |
|
35
|
|
|
$route = $request->getAttribute('_route'); |
|
36
|
|
|
if (null === $route) { //如果没有route则直接中断 |
|
37
|
|
|
throw new \RuntimeException(sprintf('Cannot find route')); |
|
38
|
|
|
} |
|
39
|
|
|
$action = $route->getAction(); |
|
40
|
|
|
if ($action instanceof \Closure) { // 如果是可调用的结构直接返回 |
|
41
|
|
|
return $action; |
|
42
|
|
|
} |
|
43
|
|
|
return $this->createController($action); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* 创建控制器 |
|
48
|
|
|
* |
|
49
|
|
|
* @param string|array $controller |
|
50
|
|
|
* @return array |
|
51
|
|
|
*/ |
|
52
|
|
|
protected function createController($controller) |
|
53
|
|
|
{ |
|
54
|
|
|
list($class, $method) = is_string($controller) ? explode('::', $controller) : $controller; |
|
55
|
|
|
|
|
56
|
|
|
if (!class_exists($class)) { |
|
57
|
|
|
throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class)); |
|
58
|
|
|
} |
|
59
|
|
|
return [$this->configureController($this->instantiateController($class)), $method]; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* 创建控制器实例 |
|
64
|
|
|
* |
|
65
|
|
|
* @param string $class A class name |
|
66
|
|
|
* |
|
67
|
|
|
* @return object |
|
68
|
|
|
*/ |
|
69
|
|
|
protected function instantiateController($class) |
|
70
|
|
|
{ |
|
71
|
|
|
return new $class(); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
protected function configureController($controller) |
|
75
|
|
|
{ |
|
76
|
|
|
if ($controller instanceof ContainerAwareInterface) { |
|
77
|
|
|
$controller->setContainer($this->container); |
|
78
|
|
|
} |
|
79
|
|
|
return $controller; |
|
80
|
|
|
} |
|
81
|
|
|
} |