xref: /plugin/ragasker/SearchHelper.php (revision abb7d3a81e47d0abe3f1fd67ad9dcad4b861232c)
1<?php
2/**
3 * 最小限度的搜索结果处理器
4 */
5class SearchHelper {
6
7    /**
8     * 从ft_pageSearch结果中提取两个列表
9     *
10     * @param array $searchResults ft_pageSearch()返回的原始结果
11     * @return array 包含两个列表的数组
12     */
13    public function extractLists($searchResults, $maxLines = 3) {
14        $links = [];
15        $contents = [];
16
17        foreach ($searchResults as $key => $result) {
18            $normalized = $this->normalizeResult($key, $result);
19            if (!$normalized) {
20                continue;
21            }
22
23            // 1. 链接列表
24            $links[] = $this->extractLinkInfo($normalized);
25
26            // 2. 内容列表
27            $contents[] = $this->extractContentInfo($normalized, $maxLines);
28        }
29
30        return [
31            'links' => $links,
32            'contents' => $contents
33        ];
34    }
35
36    /**
37     * 提取链接信息
38     */
39    private function extractLinkInfo($result) {
40        return [
41            'id' => $result['id'],
42            'title' => $this->getPageTitle($result['id']),
43            'url' => wl($result['id']),
44            'score' => $result['score'] ?? 0,
45            'namespace' => getNS($result['id'])
46        ];
47    }
48
49    /**
50     * 提取内容信息
51     */
52    private function extractContentInfo($result, $maxLines = 3) {
53        return [
54            'id' => $result['id'],
55            'summary' => $this->getFirstLines($result['id'], $maxLines),
56            'has_content' => page_exists($result['id'])
57        ];
58    }
59
60    /**
61     * 兼容不同格式的搜索结果
62     */
63    private function normalizeResult($key, $score = null) {
64        // 结果可能是字符串(页面ID)
65        if (is_string($key) && $key !== '') {
66            return ['id' => $key, 'score' => $score];
67        }
68
69        return null;
70    }
71
72    /**
73     * 获取页面标题
74     */
75    private function getPageTitle($pageId) {
76        $title = p_get_first_heading($pageId);
77        return $title ?: $pageId;
78    }
79
80    /**
81     * 获取页面前几行作为摘要
82     */
83    private function getFirstLines($pageId, $maxLines = 3) {
84        if (!page_exists($pageId)) {
85            return '';
86        }
87
88        $content = rawWiki($pageId);
89        if ($maxLines === 0) {
90            return $content;
91        }
92
93        $lines = explode("\n", $content, $maxLines + 1);
94        return implode("\n", array_slice($lines, 0, $maxLines));
95    }
96
97    /**
98     * 使用示例
99     */
100    public function exampleUsage($searchQuery) {
101        // 1. 执行搜索
102        $highlight = false;
103        $rawResults = ft_pageSearch($searchQuery, $highlight);
104
105        // 2. 提取两个列表
106        $lists = $this->extractLists($rawResults);
107
108        // 3. 返回结果
109        return $lists;
110    }
111}
112