3 namespace MediaWiki\Widget\Search
;
10 * Renders a suggested search for the user, or tells the user
11 * a suggested search was run instead of the one provided.
13 class DidYouMeanWidget
{
14 /** @var SpecialSearch */
15 protected $specialSearch;
17 public function __construct( SpecialSearch
$specialSearch ) {
18 $this->specialSearch
= $specialSearch;
22 * @param string $term The user provided search term
23 * @param SearchResultSet $resultSet
26 public function render( $term, SearchResultSet
$resultSet ) {
27 if ( $resultSet->hasRewrittenQuery() ) {
28 $html = $this->rewrittenHtml( $term, $resultSet );
29 } elseif ( $resultSet->hasSuggestion() ) {
30 $html = $this->suggestionHtml( $resultSet );
35 return "<div class='searchdidyoumean'>$html</div>";
39 * Generates HTML shown to user when their query has been internally
40 * rewritten, and the results of the rewritten query are being returned.
42 * @param string $term The users search input
43 * @param SearchResultSet $resultSet The response to the search request
44 * @return string HTML Links the user to their original $term query, and the
45 * one suggested by $resultSet
47 protected function rewrittenHtml( $term, SearchResultSet
$resultSet ) {
49 'search' => $resultSet->getQueryAfterRewrite(),
50 // Don't magic this link into a 'go' link, it should always
51 // show search results.
54 $stParams = array_merge( $params, $this->specialSearch
->powerSearchOptions() );
56 $linkRenderer = $this->specialSearch
->getLinkRenderer();
57 $snippet = $resultSet->getQueryAfterRewriteSnippet();
58 $rewritten = $linkRenderer->makeKnownLink(
59 $this->specialSearch
->getPageTitle(),
60 $snippet ?
new HtmlArmor( $snippet ) : null,
61 [ 'id' => 'mw-search-DYM-rewritten' ],
65 $stParams['search'] = $term;
66 $stParams['runsuggestion'] = 0;
67 $original = $linkRenderer->makeKnownLink(
68 $this->specialSearch
->getPageTitle(),
70 [ 'id' => 'mw-search-DYM-original' ],
74 return $this->specialSearch
->msg( 'search-rewritten' )
75 ->rawParams( $rewritten, $original )
80 * Generates HTML shown to the user when we have a suggestion about
81 * a query that might give more/better results than their current
84 * @param SearchResultSet $resultSet
87 protected function suggestionHtml( SearchResultSet
$resultSet ) {
89 'search' => $resultSet->getSuggestionQuery(),
92 $stParams = array_merge( $params, $this->specialSearch
->powerSearchOptions() );
94 $snippet = $resultSet->getSuggestionSnippet();
95 $suggest = $this->specialSearch
->getLinkRenderer()->makeKnownLink(
96 $this->specialSearch
->getPageTitle(),
97 $snippet ?
new HtmlArmor( $snippet ) : null,
98 [ 'id' => 'mw-search-DYM-suggestion' ],
102 return $this->specialSearch
->msg( 'search-suggest' )
103 ->rawParams( $suggest )->parse();