Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.14% covered (warning)
82.14%
69 / 84
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SearchApi
83.13% covered (warning)
83.13%
69 / 83
25.00% covered (danger)
25.00%
1 / 4
18.39
0.00% covered (danger)
0.00%
0 / 1
 checkDependenciesSet
25.00% covered (danger)
25.00%
1 / 4
0.00% covered (danger)
0.00%
0 / 1
6.80
 buildCommonApiParams
85.71% covered (warning)
85.71%
30 / 35
0.00% covered (danger)
0.00%
0 / 1
3.03
 buildProfileApiParam
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
6
 buildSearchEngine
64.71% covered (warning)
64.71%
11 / 17
0.00% covered (danger)
0.00%
0 / 1
6.10
 getSearchProfileParams
n/a
0 / 0
n/a
0 / 0
0
 getContext
n/a
0 / 0
n/a
0 / 0
0
1<?php
2
3/**
4 * @license GPL-2.0-or-later
5 * @file
6 * @since 1.28
7 */
8
9namespace MediaWiki\Api;
10
11use LogicException;
12use MediaWiki\Context\IContextSource;
13use MediaWiki\Search\SearchEngine;
14use MediaWiki\Search\SearchEngineConfig;
15use MediaWiki\Search\SearchEngineFactory;
16use Wikimedia\ParamValidator\ParamValidator;
17use Wikimedia\ParamValidator\TypeDef\IntegerDef;
18
19/**
20 * Traits for API components that use a SearchEngine.
21 * @ingroup API
22 */
23trait SearchApi {
24
25    private ?SearchEngineConfig $searchEngineConfig = null;
26    private ?SearchEngineFactory $searchEngineFactory = null;
27
28    private function checkDependenciesSet() {
29        // Since this is a trait, we can't have a constructor where the services
30        // that we need are injected. Instead, the api modules that use this trait
31        // are responsible for setting them (since api modules *can* have services
32        // injected). Double check that the api module did indeed set them
33        if ( $this->searchEngineConfig === null || $this->searchEngineFactory === null ) {
34            throw new LogicException(
35                'SearchApi requires both a SearchEngineConfig and SearchEngineFactory to be set'
36            );
37        }
38    }
39
40    /**
41     * When $wgSearchType is null, $wgSearchAlternatives[0] is null. Null isn't
42     * a valid option for an array for PARAM_TYPE, so we'll use a fake name
43     * that can't possibly be a class name and describes what the null behavior
44     * does
45     */
46    private const BACKEND_NULL_PARAM = 'database-backed';
47
48    /**
49     * The set of api parameters that are shared between api calls that
50     * call the SearchEngine. Primarily this defines parameters that
51     * are utilized by self::buildSearchEngine().
52     *
53     * @param bool $isScrollable True if the api offers scrolling
54     * @return array
55     */
56    public function buildCommonApiParams( $isScrollable = true ) {
57        $this->checkDependenciesSet();
58
59        $params = [
60            'search' => [
61                ParamValidator::PARAM_TYPE => 'string',
62                ParamValidator::PARAM_REQUIRED => true,
63            ],
64            'namespace' => [
65                ParamValidator::PARAM_DEFAULT => NS_MAIN,
66                ParamValidator::PARAM_TYPE => 'namespace',
67                ParamValidator::PARAM_ISMULTI => true,
68            ],
69            'limit' => [
70                ParamValidator::PARAM_DEFAULT => 10,
71                ParamValidator::PARAM_TYPE => 'limit',
72                IntegerDef::PARAM_MIN => 1,
73                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
74                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2,
75            ],
76        ];
77        if ( $isScrollable ) {
78            $params['offset'] = [
79                ParamValidator::PARAM_DEFAULT => 0,
80                IntegerDef::PARAM_MIN => 0,
81                ParamValidator::PARAM_TYPE => 'integer',
82                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
83            ];
84        }
85
86        $alternatives = $this->searchEngineConfig->getSearchTypes();
87        if ( count( $alternatives ) > 1 ) {
88            $alternatives[0] ??= self::BACKEND_NULL_PARAM;
89            $params['backend'] = [
90                ParamValidator::PARAM_DEFAULT => $this->searchEngineConfig->getSearchType(),
91                ParamValidator::PARAM_TYPE => $alternatives,
92            ];
93            // @todo: support profile selection when multiple
94            // backends are available. The solution could be to
95            // merge all possible profiles and let ApiBase
96            // subclasses do the check. Making ApiHelp and ApiSandbox
97            // comprehensive might be more difficult.
98        } else {
99            $params += $this->buildProfileApiParam();
100        }
101
102        return $params;
103    }
104
105    /**
106     * Build the profile api param definitions. Makes bold assumption only one search
107     * engine is available, ensure that is true before calling.
108     *
109     * @return array array containing available additional api param definitions.
110     *  Empty if profiles are not supported by the searchEngine implementation.
111     * @suppress PhanTypeMismatchDimFetch
112     */
113    private function buildProfileApiParam() {
114        $this->checkDependenciesSet();
115
116        $configs = $this->getSearchProfileParams();
117        $searchEngine = $this->searchEngineFactory->create();
118        $params = [];
119        foreach ( $configs as $paramName => $paramConfig ) {
120            $profiles = $searchEngine->getProfiles(
121                $paramConfig['profile-type'],
122                $this->getContext()->getUser()
123            );
124            if ( !$profiles ) {
125                continue;
126            }
127
128            $types = [];
129            $helpMessages = [];
130            $defaultProfile = null;
131            foreach ( $profiles as $profile ) {
132                $types[] = $profile['name'];
133                if ( isset( $profile['desc-message'] ) ) {
134                    $helpMessages[$profile['name']] = $profile['desc-message'];
135                }
136
137                if ( !empty( $profile['default'] ) ) {
138                    $defaultProfile = $profile['name'];
139                }
140            }
141
142            $params[$paramName] = [
143                ParamValidator::PARAM_TYPE => $types,
144                ApiBase::PARAM_HELP_MSG => $paramConfig['help-message'],
145                ApiBase::PARAM_HELP_MSG_PER_VALUE => $helpMessages,
146                ParamValidator::PARAM_DEFAULT => $defaultProfile,
147            ];
148        }
149
150        return $params;
151    }
152
153    /**
154     * Build the search engine to use.
155     * If $params is provided then the following searchEngine options
156     * will be set:
157     *  - backend: which search backend to use
158     *  - limit: mandatory
159     *  - offset: optional
160     *  - namespace: mandatory
161     *  - search engine profiles defined by SearchApi::getSearchProfileParams()
162     * @param array|null $params API request params (must be sanitized by
163     * ApiBase::extractRequestParams() before)
164     * @return SearchEngine
165     */
166    public function buildSearchEngine( ?array $params = null ) {
167        $this->checkDependenciesSet();
168
169        if ( $params == null ) {
170            return $this->searchEngineFactory->create();
171        }
172
173        $type = $params['backend'] ?? null;
174        if ( $type === self::BACKEND_NULL_PARAM ) {
175            $type = null;
176        }
177        $searchEngine = $this->searchEngineFactory->create( $type );
178        $searchEngine->setNamespaces( $params['namespace'] );
179        $searchEngine->setLimitOffset( $params['limit'], $params['offset'] ?? 0 );
180
181        // Initialize requested search profiles.
182        $configs = $this->getSearchProfileParams();
183        foreach ( $configs as $paramName => $paramConfig ) {
184            if ( isset( $params[$paramName] ) ) {
185                $searchEngine->setFeatureData(
186                    $paramConfig['profile-type'],
187                    $params[$paramName]
188                );
189            }
190        }
191        return $searchEngine;
192    }
193
194    /**
195     * @return array[] array of arrays mapping from parameter name to a two value map
196     *  containing 'help-message' and 'profile-type' keys.
197     */
198    abstract public function getSearchProfileParams();
199
200    /**
201     * @return IContextSource
202     */
203    abstract public function getContext();
204}
205
206/** @deprecated class alias since 1.43 */
207class_alias( SearchApi::class, 'SearchApi' );