Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
50 / 55
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiQueryFunctions
90.91% covered (success)
90.91%
50 / 55
0.00% covered (danger)
0.00%
0 / 1
19.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
n/a
0 / 0
n/a
0 / 0
1
 run
90.91% covered (success)
90.91%
50 / 55
0.00% covered (danger)
0.00%
0 / 1
15.17
 getAllowedParams
n/a
0 / 0
n/a
0 / 0
2
 getExamplesMessages
n/a
0 / 0
n/a
0 / 0
1
1<?php
2/**
3 * WikiLambda API to search functions
4 *
5 * @file
6 * @ingroup Extensions
7 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
8 * @license MIT
9 */
10
11namespace MediaWiki\Extension\WikiLambda\ActionAPI;
12
13use MediaWiki\Api\ApiBase;
14use MediaWiki\Api\ApiQuery;
15use MediaWiki\Extension\WikiLambda\Registry\ZLangRegistry;
16use MediaWiki\Extension\WikiLambda\WikiLambdaServices;
17use MediaWiki\Extension\WikiLambda\ZObjectStore;
18use MediaWiki\Extension\WikiLambda\ZObjectUtils;
19use MediaWiki\Language\LanguageFallback;
20use MediaWiki\Title\Title;
21use Wikimedia\ParamValidator\ParamValidator;
22use Wikimedia\ParamValidator\TypeDef\IntegerDef;
23
24class ApiQueryFunctions extends WikiLambdaApiQueryGeneratorBase {
25
26    protected ZLangRegistry $langRegistry;
27
28    /**
29     * @codeCoverageIgnore
30     */
31    public function __construct(
32        ApiQuery $query,
33        string $moduleName,
34        protected readonly LanguageFallback $languageFallback,
35        protected readonly ZObjectStore $zObjectStore
36    ) {
37        parent::__construct( $query, $moduleName, 'wikilambdasearch_functions_' );
38
39        $this->langRegistry = ZLangRegistry::singleton();
40    }
41
42    /**
43     * @inheritDoc
44     */
45    protected function run( $resultPageSet = null ) {
46        [
47            'search' => $searchTerm,
48            'language' => $language,
49            'renderable' => $renderable,
50            'input_types' => $inputTypes,
51            'output_type' => $outputType,
52            'limit' => $limit,
53            'continue' => $continue,
54        ] = $this->extractRequestParams();
55
56        $languageZids = $this->langRegistry->getListOfFallbackLanguageZids( $this->languageFallback, $language );
57        $outputType = $outputType ?: null;
58        $inputArray = $inputTypes ? array_count_values( $inputTypes ) : [];
59
60        $res = $this->zObjectStore->searchFunctions(
61            $searchTerm,
62            $languageZids,
63            $renderable,
64            $inputArray,
65            $outputType
66        );
67
68        // 1. Set match_rate for every entry and eliminate duplicates with lower match rates
69        $matches = [];
70        $hasSearchTerm = ( $searchTerm !== '' );
71        $matchField = ZObjectUtils::isValidZObjectReference( $searchTerm ) ? 'wlzl_zobject_zid' : 'wlzl_label';
72
73        foreach ( $res as $row ) {
74            $matchRate = $hasSearchTerm ? self::getMatchRate( $searchTerm, $row->{ $matchField } ) : 0;
75
76            // If the current row is new or a better match, keep. Else, ignore.
77            if ( !array_key_exists( $row->wlzl_zobject_zid, $matches ) ||
78                ( $matches[ $row->wlzl_zobject_zid ][ 'match_rate' ] < $matchRate ) ) {
79                $matches[ $row->wlzl_zobject_zid ] = [
80                    'page_id' => $row->page_id,
81                    // TODO (T258915): When we support redirects, implement.
82                    'page_is_redirect' => false,
83                    'page_namespace' => NS_MAIN,
84                    'page_content_model' => CONTENT_MODEL_ZOBJECT,
85                    'page_title' => $row->wlzl_zobject_zid,
86                    'match_label' => $hasSearchTerm ? $row->{ $matchField } : null,
87                    'match_lang' => $hasSearchTerm ? $row->wlzl_language : null,
88                    'match_rate' => $matchRate,
89                    'label' => $row->preferred_label,
90                    'language' => $row->preferred_language
91                ];
92            }
93        }
94
95        // 2. Sort all results by match_rate to get best hits
96        usort( $matches, static function ( $a, $b ) {
97            return $b[ 'match_rate' ] <=> $a[ 'match_rate' ];
98        } );
99
100        // 3. Prune the result set to the limit, slice to requested page, and set continue
101        $continue = $continue === null ? 0 : intval( $continue );
102        $hits = array_slice( $matches, $continue * $limit, $limit );
103        $pageSize = count( $matches ) - ( $continue * $limit );
104        if ( $pageSize > $limit ) {
105            $this->setContinueEnumParameter( 'continue', strval( $continue + 1 ) );
106        }
107
108        if ( $resultPageSet ) {
109            foreach ( $hits as $index => $entry ) {
110                $resultPageSet->setGeneratorData(
111                    Title::makeTitle( $entry['page_namespace'], $entry['page_title'] ),
112                    [ 'index' => $index + $continue + 1 ]
113                );
114            }
115        } else {
116            $result = $this->getResult();
117            foreach ( $hits as $entry ) {
118                $result->addValue( [ 'query', $this->getModuleName() ], null, $entry );
119            }
120        }
121    }
122
123    /**
124     * @inheritDoc
125     * @codeCoverageIgnore
126     */
127    protected function getAllowedParams(): array {
128        // Don't try to read the supported languages from the DB on client wikis, we can't.
129        $supportedLanguageCodes =
130            ( WikiLambdaServices::getMode()->isRepo() ) ?
131            $this->zObjectStore->fetchAllZLanguageCodes() :
132            [];
133
134        return [
135            'search' => [
136                ParamValidator::PARAM_TYPE => 'string',
137                ParamValidator::PARAM_DEFAULT => '',
138            ],
139            'language' => [
140                ParamValidator::PARAM_TYPE => $supportedLanguageCodes,
141                ParamValidator::PARAM_REQUIRED => true,
142            ],
143            'renderable' => [
144                ParamValidator::PARAM_TYPE => 'boolean',
145                ParamValidator::PARAM_DEFAULT => false,
146            ],
147            'input_types' => [
148                ParamValidator::PARAM_TYPE => 'string',
149                ParamValidator::PARAM_ISMULTI => true,
150                ParamValidator::PARAM_ALLOW_DUPLICATES => true,
151                ParamValidator::PARAM_REQUIRED => false,
152            ],
153            'output_type' => [
154                ParamValidator::PARAM_TYPE => 'string',
155                ParamValidator::PARAM_REQUIRED => false,
156            ],
157            'limit' => [
158                ParamValidator::PARAM_TYPE => 'limit',
159                ParamValidator::PARAM_DEFAULT => 10,
160                IntegerDef::PARAM_MIN => 1,
161                IntegerDef::PARAM_MAX => ApiBase::LIMIT_BIG1,
162                IntegerDef::PARAM_MAX2 => ApiBase::LIMIT_BIG2,
163            ],
164            'continue' => [
165                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
166            ],
167        ];
168    }
169
170    /**
171     * @inheritDoc
172     * @codeCoverageIgnore
173     */
174    protected function getExamplesMessages() {
175        return [
176            // Functions with label that matches 'Engl' and have renderable IOs
177            'action=query&list=wikilambdasearch_functions'
178            . '&wikilambdasearch_functions_search=Engl'
179            . '&wikilambdasearch_functions_language=en'
180            . '&wikilambdasearch_functions_renderable=1'
181            => 'apihelp-query+wikilambdasearch_functions-example-renderable',
182            // Functions that have at least two String inputs and output String
183            'action=query&list=wikilambdasearch_functions'
184            . '&wikilambdasearch_functions_language=en'
185            . '&wikilambdasearch_functions_input_types=Z6%7CZ6'
186            . '&wikilambdasearch_functions_output_type=Z6'
187            => 'apihelp-query+wikilambdasearch_functions-example-io-types',
188        ];
189    }
190}