1<?php
2
3
4namespace ComboStrap;
5
6
7class Index
8{
9    /**
10     * @var Index
11     */
12    private static $index;
13
14    /**
15     * @var \dokuwiki\Search\Indexer
16     */
17    private $indexer;
18
19
20    /**
21     * Index constructor.
22     */
23    public function __construct()
24    {
25        $this->indexer = idx_get_indexer();
26    }
27
28    public static function getOrCreate(): Index
29    {
30        if (self::$index === null) {
31            self::$index = new Index();
32        }
33        return self::$index;
34    }
35
36    public function getPagesForMedia(WikiPath $media): array
37    {
38        $dokuwikiId = $media->getWikiId();
39        return $this->indexer->lookupKey('relation_media', $dokuwikiId);
40    }
41
42    /**
43     * Return a list of page id that have the same last name
44     *
45     * @param MarkupPath $pageToMatch
46     * @return MarkupPath[]
47     */
48    public function getPagesWithSameLastName(MarkupPath $pageToMatch): array
49    {
50        /**
51         * * A shortcut to:
52         * ```
53         * $pagesWithSameName = ft_pageLookup($pageName);
54         * ```
55         * where {@link ft_pageLookup()}
56         */
57
58        try {
59            $lastNameToFind = $pageToMatch->getPathObject()->getLastNameWithoutExtension();
60            $wikiIdToFind = $pageToMatch->getWikiId();
61        } catch (ExceptionNotFound|ExceptionBadArgument $e) {
62            return [];
63        }
64
65        // There is two much pages with the start name
66        if ($lastNameToFind === Site::getIndexPageName()) {
67            return [];
68        }
69
70        $pageIdList = $this->indexer->getPages();
71
72        $matchedPages = [];
73        foreach ($pageIdList as $pageId) {
74            if ($wikiIdToFind === $pageId) {
75                // don't return the page to find in the result
76                continue;
77            }
78            $actualPage = WikiPath::createMarkupPathFromId($pageId);
79            try {
80                if ($actualPage->getLastNameWithoutExtension() === $lastNameToFind) {
81                    $matchedPages[] = MarkupPath::createPageFromPathObject($actualPage);
82                }
83            } catch (ExceptionNotFound $e) {
84                // root, should not happen
85            }
86        }
87        return $matchedPages;
88
89    }
90
91    public function deletePage(MarkupPath $page)
92    {
93
94        $this->indexer->deletePage($page->getWikiId());
95
96    }
97}
98