]> git.mxchange.org Git - friendica.git/blob - src/App/Router.php
f723321ac67cf883bfe8a2ab93c26c5e77c78b7c
[friendica.git] / src / App / Router.php
1 <?php
2
3 namespace Friendica\App;
4
5
6 use FastRoute\DataGenerator\GroupCountBased;
7 use FastRoute\Dispatcher;
8 use FastRoute\RouteCollector;
9 use FastRoute\RouteParser\Std;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Network\HTTPException;
13
14 /**
15  * Wrapper for FastRoute\Router
16  *
17  * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
18  * module class.
19  *
20  * Actual routes are defined in App->collectRoutes.
21  *
22  * @package Friendica\App
23  */
24 class Router
25 {
26         const POST = 'POST';
27         const GET  = 'GET';
28
29         const ALLOWED_METHODS = [
30                 self::POST,
31                 self::GET,
32         ];
33
34         /** @var RouteCollector */
35         protected $routeCollector;
36
37         /**
38          * @var string The HTTP method
39          */
40         private $httpMethod;
41
42         /**
43          * @param array $server The $_SERVER variable
44          * @param RouteCollector|null $routeCollector Optional the loaded Route collector
45          */
46         public function __construct(array $server, RouteCollector $routeCollector = null)
47         {
48                 $httpMethod = $server['REQUEST_METHOD'] ?? self::GET;
49                 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
50
51                 $this->routeCollector = isset($routeCollector) ?
52                         $routeCollector :
53                         new RouteCollector(new Std(), new GroupCountBased());
54         }
55
56         /**
57          * @param array $routes The routes to add to the Router
58          *
59          * @return self The router instance with the loaded routes
60          *
61          * @throws HTTPException\InternalServerErrorException In case of invalid configs
62          */
63         public function addRoutes(array $routes)
64         {
65                 $routeCollector = (isset($this->routeCollector) ?
66                         $this->routeCollector :
67                         new RouteCollector(new Std(), new GroupCountBased()));
68
69                 foreach ($routes as $route => $config) {
70                         if ($this->isGroup($config)) {
71                                 $this->addGroup($route, $config, $routeCollector);
72                         } elseif ($this->isRoute($config)) {
73                                 $routeCollector->addRoute($config[1], $route, $config[0]);
74                         } else {
75                                 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
76                         }
77                 }
78
79                 $this->routeCollector = $routeCollector;
80
81                 return $this;
82         }
83
84         /**
85          * Adds a group of routes to a given group
86          *
87          * @param string         $groupRoute     The route of the group
88          * @param array          $routes         The routes of the group
89          * @param RouteCollector $routeCollector The route collector to add this group
90          */
91         private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
92         {
93                 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
94                         foreach ($routes as $route => $config) {
95                                 if ($this->isGroup($config)) {
96                                         $this->addGroup($route, $config, $routeCollector);
97                                 } elseif ($this->isRoute($config)) {
98                                         $routeCollector->addRoute($config[1], $route, $config[0]);
99                                 }else {
100                                         throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
101                                 }
102                         }
103                 });
104         }
105
106         /**
107          * Returns true in case the config is a group config
108          *
109          * @param array $config
110          *
111          * @return bool
112          */
113         private function isGroup(array $config)
114         {
115                 return
116                         is_array($config) &&
117                         is_string(array_keys($config)[0]) &&
118                         // This entry should NOT be a BaseModule
119                         (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
120                         // The second argument is an array (another routes)
121                         is_array(array_values($config)[0]);
122         }
123
124         /**
125          * Returns true in case the config is a route config
126          *
127          * @param array $config
128          *
129          * @return bool
130          */
131         private function isRoute(array $config)
132         {
133                 return
134                         // The config array should at least have one entry
135                         !empty($config[0]) &&
136                         // This entry should be a BaseModule
137                         (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
138                         // Either there is no other argument
139                         (empty($config[1]) ||
140                          // Or the second argument is an array (HTTP-Methods)
141                          is_array($config[1]));
142         }
143
144         /**
145          * The current route collector
146          *
147          * @return RouteCollector|null
148          */
149         public function getRouteCollector()
150         {
151                 return $this->routeCollector;
152         }
153
154         /**
155          * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
156          *
157          * @param string $cmd The path component of the request URL without the query string
158          *
159          * @return string A Friendica\BaseModule-extending class name if a route rule matched
160          *
161          * @throws HTTPException\InternalServerErrorException
162          * @throws HTTPException\MethodNotAllowedException    If a rule matched but the method didn't
163          * @throws HTTPException\NotFoundException            If no rule matched
164          */
165         public function getModuleClass($cmd)
166         {
167                 // Add routes from addons
168                 Hook::callAll('route_collection', $this->routeCollector);
169
170                 $cmd = '/' . ltrim($cmd, '/');
171
172                 $dispatcher = new \FastRoute\Dispatcher\GroupCountBased($this->routeCollector->getData());
173
174                 $moduleClass = null;
175
176                 $routeInfo  = $dispatcher->dispatch($this->httpMethod, $cmd);
177                 if ($routeInfo[0] === Dispatcher::FOUND) {
178                         $moduleClass = $routeInfo[1];
179                 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
180                         throw new HTTPException\MethodNotAllowedException(L10n::t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
181                 } else {
182                         throw new HTTPException\NotFoundException(L10n::t('Page not found.'));
183                 }
184
185                 return $moduleClass;
186         }
187 }