1<?php
2
3namespace ComboStrap;
4
5use action_plugin_combo_linkwizard;
6
7/**
8 * Function that supports the internal search functions
9 */
10class Search
11{
12
13    /**
14     * @param $searchTermWords
15     * @param array $columns
16     * @return array - the parametrized sql and the parameters
17     */
18    public static function getPageRowsSql($searchTermWords, array $columns = ["h1", "title", "name"]): array
19    {
20        $sqlParameters = [];
21        $sqlPredicates = [];
22        foreach ($searchTermWords as $searchTermWord) {
23            if (strlen($searchTermWord) < action_plugin_combo_linkwizard::MINIMAL_WORD_LENGTH) {
24                continue;
25            }
26            $pattern = "%$searchTermWord%";
27            $sqlPatternPredicates = [];
28            foreach ($columns as $column) {
29                $sqlParameters[] = $pattern;
30                $sqlPatternPredicates[] = "$column like ? COLLATE NOCASE";
31            }
32            $sqlPredicates[] = "(" . implode(" or ", $sqlPatternPredicates) . ")";
33        }
34        $sqlPredicate = implode(" and ", $sqlPredicates);
35        $searchTermSql = <<<EOF
36select id as "id" from pages where $sqlPredicate order by name
37EOF;
38        return [$searchTermSql, $sqlParameters];
39    }
40
41    /**
42     * @param $searchTerm
43     * @param array $columns
44     * @return MarkupPath[]
45     */
46    public static function getPages($searchTerm, array $columns = ["h1", "title", "name"]): array
47    {
48        $minimalWordLength = action_plugin_combo_linkwizard::MINIMAL_WORD_LENGTH;
49        if (strlen($searchTerm) < $minimalWordLength) {
50            return [];
51        }
52        $searchTermWords = StringUtility::getWords($searchTerm);
53        if (sizeOf($searchTermWords) === 0) {
54            return [];
55        }
56        try {
57            $sqlite = Sqlite::createOrGetSqlite();
58        } catch (ExceptionSqliteNotAvailable $e) {
59            return [];
60        }
61        [$searchTermSql, $sqlParameters] = self::getPageRowsSql($searchTermWords, $columns);
62        $request = $sqlite
63            ->createRequest()
64            ->setQueryParametrized($searchTermSql, $sqlParameters);
65        $pages = [];
66        try {
67            $rows = $request
68                ->execute()
69                ->getRows();
70            foreach ($rows as $row) {
71                $pages[] = MarkupPath::createMarkupFromId($row["id"]);
72            }
73            return $pages;
74        } catch (ExceptionCompile $e) {
75            LogUtility::msg("Error while trying to retrieve a list of pages", LogUtility::LVL_MSG_ERROR, action_plugin_combo_linkwizard::CANONICAL);
76            return $pages;
77        } finally {
78            $request->close();
79        }
80    }
81}
82