3 namespace MediaWiki\Rest
;
7 use MediaWiki\Rest\PathTemplateMatcher\PathMatcher
;
8 use Wikimedia\ObjectFactory
;
11 * The REST router is responsible for gathering handler configuration, matching
12 * an input path and HTTP method against the defined routes, and constructing
13 * and executing the relevant handler for a request.
22 /** @var array|null */
23 private $routesFromFiles;
25 /** @var int[]|null */
26 private $routeFileTimestamps;
31 /** @var \BagOStuff */
34 /** @var PathMatcher[]|null Path matchers by method */
37 /** @var string|null */
40 /** @var ResponseFactory */
41 private $responseFactory;
44 * @param string[] $routeFiles List of names of JSON files containing routes
45 * @param array $extraRoutes Extension route array
46 * @param string $rootPath The base URL path
47 * @param BagOStuff $cacheBag A cache in which to store the matcher trees
48 * @param ResponseFactory $responseFactory
50 public function __construct( $routeFiles, $extraRoutes, $rootPath,
51 BagOStuff
$cacheBag, ResponseFactory
$responseFactory
53 $this->routeFiles
= $routeFiles;
54 $this->extraRoutes
= $extraRoutes;
55 $this->rootPath
= $rootPath;
56 $this->cacheBag
= $cacheBag;
57 $this->responseFactory
= $responseFactory;
61 * Get the cache data, or false if it is missing or invalid
65 private function fetchCacheData() {
66 $cacheData = $this->cacheBag
->get( $this->getCacheKey() );
67 if ( $cacheData && $cacheData['CONFIG-HASH'] === $this->getConfigHash() ) {
68 unset( $cacheData['CONFIG-HASH'] );
76 * @return string The cache key
78 private function getCacheKey() {
79 return $this->cacheBag
->makeKey( __CLASS__
, '1' );
83 * Get a config version hash for cache invalidation
87 private function getConfigHash() {
88 if ( $this->configHash
=== null ) {
89 $this->configHash
= md5( json_encode( [
91 $this->getRouteFileTimestamps()
94 return $this->configHash
;
98 * Load the defined JSON files and return the merged routes
102 private function getRoutesFromFiles() {
103 if ( $this->routesFromFiles
=== null ) {
104 $this->routeFileTimestamps
= [];
105 foreach ( $this->routeFiles
as $fileName ) {
106 $this->routeFileTimestamps
[$fileName] = filemtime( $fileName );
107 $routes = json_decode( file_get_contents( $fileName ), true );
108 if ( $this->routesFromFiles
=== null ) {
109 $this->routesFromFiles
= $routes;
111 $this->routesFromFiles
= array_merge( $this->routesFromFiles
, $routes );
115 return $this->routesFromFiles
;
119 * Get an array of last modification times of the defined route files.
121 * @return int[] Last modification times
123 private function getRouteFileTimestamps() {
124 if ( $this->routeFileTimestamps
=== null ) {
125 $this->routeFileTimestamps
= [];
126 foreach ( $this->routeFiles
as $fileName ) {
127 $this->routeFileTimestamps
[$fileName] = filemtime( $fileName );
130 return $this->routeFileTimestamps
;
134 * Get an iterator for all defined routes, including loading the routes from
137 * @return AppendIterator
139 private function getAllRoutes() {
140 $iterator = new AppendIterator
;
141 $iterator->append( new \
ArrayIterator( $this->getRoutesFromFiles() ) );
142 $iterator->append( new \
ArrayIterator( $this->extraRoutes
) );
147 * Get an array of PathMatcher objects indexed by HTTP method
149 * @return PathMatcher[]
151 private function getMatchers() {
152 if ( $this->matchers
=== null ) {
153 $cacheData = $this->fetchCacheData();
156 foreach ( $cacheData as $method => $data ) {
157 $matchers[$method] = PathMatcher
::newFromCache( $data );
160 foreach ( $this->getAllRoutes() as $spec ) {
161 $methods = $spec['method'] ??
[ 'GET' ];
162 if ( !is_array( $methods ) ) {
163 $methods = [ $methods ];
165 foreach ( $methods as $method ) {
166 if ( !isset( $matchers[$method] ) ) {
167 $matchers[$method] = new PathMatcher
;
169 $matchers[$method]->add( $spec['path'], $spec );
173 $cacheData = [ 'CONFIG-HASH' => $this->getConfigHash() ];
174 foreach ( $matchers as $method => $matcher ) {
175 $cacheData[$method] = $matcher->getCacheData();
177 $this->cacheBag
->set( $this->getCacheKey(), $cacheData );
179 $this->matchers
= $matchers;
181 return $this->matchers
;
185 * Remove the path prefix $this->rootPath. Return the part of the path with the
186 * prefix removed, or false if the prefix did not match.
188 * @param string $path
189 * @return false|string
191 private function getRelativePath( $path ) {
192 if ( substr_compare( $path, $this->rootPath
, 0, strlen( $this->rootPath
) ) !== 0 ) {
195 return substr( $path, strlen( $this->rootPath
) );
199 * Find the handler for a request and execute it
201 * @param RequestInterface $request
202 * @return ResponseInterface
204 public function execute( RequestInterface
$request ) {
205 $path = $request->getUri()->getPath();
206 $relPath = $this->getRelativePath( $path );
207 if ( $relPath === false ) {
208 return $this->responseFactory
->createHttpError( 404 );
211 $matchers = $this->getMatchers();
212 $matcher = $matchers[$request->getMethod()] ??
null;
213 $match = $matcher ?
$matcher->match( $relPath ) : null;
216 // Check for 405 wrong method
218 foreach ( $matchers as $allowedMethod => $allowedMatcher ) {
219 if ( $allowedMethod === $request->getMethod() ) {
222 if ( $allowedMatcher->match( $relPath ) ) {
223 $allowed[] = $allowedMethod;
227 $response = $this->responseFactory
->createHttpError( 405 );
228 $response->setHeader( 'Allow', $allowed );
231 // Did not match with any other method, must be 404
232 return $this->responseFactory
->createHttpError( 404 );
236 $request->setPathParams( $match['params'] );
237 $spec = $match['userData'];
238 $objectFactorySpec = array_intersect_key( $spec,
239 [ 'factory' => true, 'class' => true, 'args' => true ] );
240 /** @var $handler Handler (annotation for PHPStorm) */
241 $handler = ObjectFactory
::getObjectFromSpec( $objectFactorySpec );
242 $handler->init( $this, $request, $spec, $this->responseFactory
);
245 return $this->executeHandler( $handler );
246 } catch ( HttpException
$e ) {
247 return $this->responseFactory
->createFromException( $e );
252 * Execute a fully-constructed handler
253 * @param Handler $handler
254 * @return ResponseInterface
256 private function executeHandler( $handler ): ResponseInterface
{
257 $response = $handler->execute();
258 if ( !( $response instanceof ResponseInterface
) ) {
259 $response = $this->responseFactory
->createFromReturnValue( $response );