xref: /dokuwiki/inc/Search/Query/NamespacePredicate.php (revision 21fbd01b3c3eea88b767376b7b158f31f0f63127)
1<?php
2
3namespace dokuwiki\Search\Query;
4
5/**
6 * A namespace prefix used to filter pages by their ID
7 *
8 * The prefix always includes a trailing colon (e.g., "wiki:") to ensure
9 * exact namespace matching — "wiki:" won't match "wikipedia:page".
10 */
11class NamespacePredicate implements StackEntry
12{
13    protected string $prefix;
14
15    /**
16     * @param string $prefix namespace prefix including trailing colon
17     */
18    public function __construct(string $prefix)
19    {
20        $this->prefix = $prefix;
21    }
22
23    /**
24     * @return string the namespace prefix
25     */
26    public function getPrefix(): string
27    {
28        return $this->prefix;
29    }
30
31    /**
32     * Keep only pages whose ID starts with this namespace prefix
33     */
34    public function filter(PageSet $pages): PageSet
35    {
36        $result = [];
37        foreach ($pages->getPages() as $id => $score) {
38            if (str_starts_with($id, $this->prefix)) {
39                $result[$id] = $score;
40            }
41        }
42        return new PageSet($result);
43    }
44
45    /**
46     * Keep only pages whose ID does NOT start with this namespace prefix
47     */
48    public function exclude(PageSet $pages): PageSet
49    {
50        $result = [];
51        foreach ($pages->getPages() as $id => $score) {
52            if (!str_starts_with($id, $this->prefix)) {
53                $result[$id] = $score;
54            }
55        }
56        return new PageSet($result);
57    }
58}
59