Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.00% covered (warning)
75.00%
72 / 96
54.55% covered (warning)
54.55%
6 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
SpecBasedModule
75.00% covered (warning)
75.00%
72 / 96
54.55% covered (warning)
54.55%
6 / 11
31.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 getConfigHash
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getModuleDefinition
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 loadModuleDefinition
58.82% covered (warning)
58.82%
10 / 17
0.00% covered (danger)
0.00%
0 / 1
6.75
 getRouteFileTimestamp
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getDefinedPaths
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 initRoutes
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 makeRouteInfo
97.06% covered (success)
97.06%
33 / 34
0.00% covered (danger)
0.00%
0 / 1
3
 getOpenApiInfo
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getOpenApiExternalDocs
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getOpenApiTags
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace MediaWiki\Rest\Module;
4
5use MediaWiki\HookContainer\HookContainer;
6use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface;
7use MediaWiki\Rest\Handler\RedirectHandler;
8use MediaWiki\Rest\JsonLocalizer;
9use MediaWiki\Rest\PathTemplateMatcher\ModuleConfigurationException;
10use MediaWiki\Rest\Reporter\ErrorReporter;
11use MediaWiki\Rest\RouteDefinitionException;
12use MediaWiki\Rest\Router;
13use MediaWiki\Rest\Validator\Validator;
14use Wikimedia\ObjectFactory\ObjectFactory;
15
16/**
17 * A Module that is based on a module definition file similar to an OpenAPI spec.
18 * @see docs/rest/mwapi-1.0.json for the schema of module definition files.
19 *
20 * Just like an OpenAPI spec, the module definition file contains a "paths"
21 * section that maps paths and HTTP methods to operations. Each operation
22 * then specifies the PHP class that will handle the request under the "handler"
23 * key. The value of the "handler" key is an object spec for use with
24 * ObjectFactory::createObject.
25 *
26 * The following fields are supported as a shorthand notation:
27 * - "redirect": the route represents a redirect and will be handled by
28 *   the RedirectHandler class. The redirect is specified as a JSON object
29 *   that specifies the target "path", and optional the redirect "code".
30 *   If a redirect is defined, the "handler" key must be omitted.
31 *
32 * More shorthands may be added in the future.
33 *
34 * Route definitions can contain additional fields to configure the handler.
35 * The handler can access the route definition by calling getConfig().
36 *
37 * @internal
38 * @since 1.43
39 */
40class SpecBasedModule extends MatcherBasedModule {
41
42    private ?array $moduleDef = null;
43
44    private ?int $routeFileTimestamp = null;
45
46    private ?string $configHash = null;
47
48    /**
49     * @internal
50     */
51    public function __construct(
52        private readonly string $definitionFile,
53        Router $router,
54        string $pathPrefix,
55        JsonLocalizer $jsonLocalizer,
56        BasicAuthorizerInterface $basicAuth,
57        ObjectFactory $objectFactory,
58        Validator $restValidator,
59        ErrorReporter $errorReporter,
60        HookContainer $hookContainer,
61    ) {
62        parent::__construct(
63            $router,
64            $pathPrefix,
65            $jsonLocalizer,
66            $basicAuth,
67            $objectFactory,
68            $restValidator,
69            $errorReporter,
70            $hookContainer
71        );
72    }
73
74    /**
75     * Get a config version hash for cache invalidation
76     */
77    protected function getConfigHash(): string {
78        if ( $this->configHash === null ) {
79            $this->configHash = md5( json_encode( [
80                'class' => __CLASS__,
81                'version' => 1,
82                'fileTimestamps' => $this->getRouteFileTimestamp()
83            ] ) );
84        }
85        return $this->configHash;
86    }
87
88    /**
89     * Load the module definition file.
90     */
91    private function getModuleDefinition(): array {
92        if ( $this->moduleDef !== null ) {
93            return $this->moduleDef;
94        }
95
96        $this->routeFileTimestamp = filemtime( $this->definitionFile );
97        $this->moduleDef = static::loadModuleDefinition(
98            $this->definitionFile,
99            $this->getJsonLocalizer()
100        );
101
102        return $this->moduleDef;
103    }
104
105    /**
106     * Load the module definition file.
107     *
108     * @param string $file The module definition file to load
109     * @param JsonLocalizer $localizer
110     *
111     * @return array
112     */
113    public static function loadModuleDefinition( string $file, JsonLocalizer $localizer ): array {
114        $moduleDef = static::loadJsonFile( $file );
115
116        // This does not guarantee the file is a valid flat route file, just that it appears
117        // to be of that format. Files containing only an empty array are assumed to be valid
118        // flat route files containing no routes rather than malformed module definition files.
119        // Some development flat route files in extensions, such as Wikibase's routes.dev.json,
120        // may exist as placeholders but intentionally contain no routes.
121        if ( array_is_list( $moduleDef ) ) {
122            throw new ModuleFormatException(
123                $file . ' appears to be a flat route file, not a module definition file.'
124            );
125        }
126
127        // The array_is_list() call above confuses phan. Force phan to consider $mwapi to be of
128        // the type we expect. Also check its type ourselves in code at runtime, just to be sure.
129        $mwapi = $moduleDef['mwapi'] ?? null;
130        '@phan-var ?string $mwapi';
131
132        if ( !is_string( $mwapi ) ) {
133            throw new ModuleConfigurationException(
134                'Missing or malformed mwapi version field in ' . $file
135            );
136        }
137
138        // Require a supported version of mwapi
139        if ( version_compare( $mwapi, '1.0.0', '<' ) ||
140            version_compare( $mwapi, '1.2.999', '>' )
141        ) {
142            throw new ModuleConfigurationException(
143                "Unsupported mwapi version {$mwapi} in "
144                . $file
145            );
146        }
147
148        return $localizer->localizeJson( $moduleDef );
149    }
150
151    /**
152     * Get last modification times of the module definition file.
153     */
154    private function getRouteFileTimestamp(): int {
155        $this->routeFileTimestamp ??= filemtime( $this->definitionFile );
156        return $this->routeFileTimestamp;
157    }
158
159    /**
160     * @unstable for testing
161     *
162     * @return array[]
163     */
164    public function getDefinedPaths(): array {
165        $paths = [];
166        $moduleDef = $this->getModuleDefinition();
167
168        foreach ( $moduleDef['paths'] as $path => $pSpec ) {
169            $paths[$path] = [];
170            foreach ( $pSpec as $method => $opSpec ) {
171                $paths[$path][] = strtoupper( $method );
172            }
173        }
174
175        return $paths;
176    }
177
178    protected function initRoutes(): void {
179        $moduleDef = $this->getModuleDefinition();
180
181        // The structure is similar to OpenAPI, see docs/rest/mwapi.1.0.json
182        foreach ( $moduleDef['paths'] as $path => $pathSpec ) {
183            foreach ( $pathSpec as $method => $opSpec ) {
184                $info = $this->makeRouteInfo( $path, $opSpec );
185                $this->addRoute( $method, $path, $info );
186            }
187        }
188    }
189
190    /**
191     * Generate a route info array to be stored in the matcher tree,
192     * in the form expected by MatcherBasedModule::addRoute()
193     * and ultimately Module::getHandlerForPath().
194     */
195    private function makeRouteInfo( string $path, array $opSpec ): array {
196        static $objectSpecKeys = [
197            'class',
198            'factory',
199            'services',
200            'optional_services',
201            'args',
202            'adapter', // for known adapter classes
203        ];
204
205        static $oasKeys = [
206            'parameters',
207            'responses',
208            'summary',
209            'description',
210            'tags',
211            'externalDocs',
212            'deprecationSettings',
213            'operationId',
214        ];
215
216        if ( isset( $opSpec['redirect'] ) ) {
217            // Redirect shorthand
218            $opSpec['handler'] = [
219                'class' => RedirectHandler::class,
220                'redirect' => $opSpec['redirect'],
221            ];
222            unset( $opSpec['redirect'] );
223        }
224
225        $handlerSpec = $opSpec['handler'] ?? null;
226        if ( !$handlerSpec ) {
227            throw new RouteDefinitionException( 'Missing handler spec' );
228        }
229
230        $info = [
231            'spec' => array_intersect_key( $handlerSpec, array_flip( $objectSpecKeys ) ),
232            'config' => array_diff_key( $handlerSpec, array_flip( $objectSpecKeys ) ),
233            'openApiSpec' => array_intersect_key( $opSpec, array_flip( $oasKeys ) ),
234            'path' => $path,
235        ];
236
237        return $info;
238    }
239
240    /** @inheritDoc */
241    public function getOpenApiInfo() {
242        $def = $this->getModuleDefinition();
243        return $def['info'] ?? [];
244    }
245
246    /** @inheritDoc */
247    public function getOpenApiExternalDocs(): array {
248        $def = $this->getModuleDefinition();
249        return $def['externalDocs'] ?? [];
250    }
251
252    /** @inheritDoc */
253    public function getOpenApiTags(): array {
254        $def = $this->getModuleDefinition();
255        return $def['tags'] ?? [];
256    }
257
258}