1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Router; |
3
|
|
|
|
4
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
5
|
|
|
use Wandu\Router\Contracts\LoaderInterface; |
6
|
|
|
use Wandu\Router\Contracts\ResponsifierInterface; |
7
|
|
|
use Wandu\Router\Contracts\RouteInformation; |
8
|
|
|
|
9
|
|
|
class RouteExecutor |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param \Wandu\Router\Contracts\LoaderInterface $loader |
13
|
|
|
* @param \Wandu\Router\Contracts\ResponsifierInterface $responsifier |
14
|
|
|
*/ |
15
|
17 |
|
public function __construct(LoaderInterface $loader, ResponsifierInterface $responsifier) |
16
|
|
|
{ |
17
|
17 |
|
$this->loader = $loader; |
|
|
|
|
18
|
17 |
|
$this->responsifier = $responsifier; |
|
|
|
|
19
|
17 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param \Wandu\Router\Contracts\RouteInformation $route |
23
|
|
|
* @param \Psr\Http\Message\ServerRequestInterface $request |
24
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
25
|
|
|
*/ |
26
|
17 |
|
public function execute(RouteInformation $route, ServerRequestInterface $request) |
27
|
|
|
{ |
28
|
17 |
|
return $this->next($request, $route->getClassName(), $route->getMethodName(), $route->getMiddlewares()); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param \Psr\Http\Message\ServerRequestInterface $request |
33
|
|
|
* @param string $className |
34
|
|
|
* @param string $methodName |
35
|
|
|
* @param array $middlewares |
36
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
37
|
|
|
*/ |
38
|
17 |
|
protected function next(ServerRequestInterface $request, $className, $methodName, array $middlewares = []) |
39
|
|
|
{ |
40
|
17 |
|
if (count($middlewares)) { |
41
|
3 |
|
$middleware = $this->loader->middleware(array_shift($middlewares), $request); |
42
|
3 |
|
$response = $middleware->__invoke($request, function (ServerRequestInterface $request) use ($className, $methodName, $middlewares) { |
43
|
2 |
|
return $this->next($request, $className, $methodName, $middlewares); |
44
|
3 |
|
}); |
45
|
3 |
|
return $this->responsifier->responsify($response); |
46
|
|
|
} |
47
|
16 |
|
return $this->responsifier->responsify( |
48
|
16 |
|
$this->loader->execute($className, $methodName, $request) |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: