1: <?php
2: namespace Ratchet\Http;
3: use Ratchet\ConnectionInterface;
4: use Psr\Http\Message\RequestInterface;
5: use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
6: use Symfony\Component\Routing\Exception\MethodNotAllowedException;
7: use Symfony\Component\Routing\Exception\ResourceNotFoundException;
8: use GuzzleHttp\Psr7 as gPsr;
9:
10: class Router implements HttpServerInterface {
11: use CloseResponseTrait;
12:
13: 14: 15:
16: protected $_matcher;
17:
18: public function __construct(UrlMatcherInterface $matcher) {
19: $this->_matcher = $matcher;
20: }
21:
22: 23: 24: 25:
26: public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) {
27: if (null === $request) {
28: throw new \UnexpectedValueException('$request can not be null');
29: }
30:
31: $uri = $request->getUri();
32:
33: $context = $this->_matcher->getContext();
34: $context->setMethod($request->getMethod());
35: $context->setHost($uri->getHost());
36:
37: try {
38: $route = $this->_matcher->match($uri->getPath());
39: } catch (MethodNotAllowedException $nae) {
40: return $this->close($conn, 405, array('Allow' => $nae->getAllowedMethods()));
41: } catch (ResourceNotFoundException $nfe) {
42: return $this->close($conn, 404);
43: }
44:
45: if (is_string($route['_controller']) && class_exists($route['_controller'])) {
46: $route['_controller'] = new $route['_controller'];
47: }
48:
49: if (!($route['_controller'] instanceof HttpServerInterface)) {
50: throw new \UnexpectedValueException('All routes must implement Ratchet\Http\HttpServerInterface');
51: }
52:
53: $parameters = [];
54: foreach($route as $key => $value) {
55: if ((is_string($key)) && ('_' !== substr($key, 0, 1))) {
56: $parameters[$key] = $value;
57: }
58: }
59: $parameters = array_merge($parameters, gPsr\parse_query($uri->getQuery() ?: ''));
60:
61: $request = $request->withUri($uri->withQuery(gPsr\build_query($parameters)));
62:
63: $conn->controller = $route['_controller'];
64: $conn->controller->onOpen($conn, $request);
65: }
66:
67: 68: 69:
70: function onMessage(ConnectionInterface $from, $msg) {
71: $from->controller->onMessage($from, $msg);
72: }
73:
74: 75: 76:
77: function onClose(ConnectionInterface $conn) {
78: if (isset($conn->controller)) {
79: $conn->controller->onClose($conn);
80: }
81: }
82:
83: 84: 85:
86: function onError(ConnectionInterface $conn, \Exception $e) {
87: if (isset($conn->controller)) {
88: $conn->controller->onError($conn, $e);
89: }
90: }
91: }
92: