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