xref: /dokuwiki/inc/Search/Query/NamespacePredicate.php (revision 9369b4a991666bc911474806b106d8958e79f4c1)
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 = array_filter(
37            $pages->getPages(),
38            fn($id) => str_starts_with($id, $this->prefix),
39            ARRAY_FILTER_USE_KEY
40        );
41        return new PageSet($result);
42    }
43
44    /**
45     * Keep only pages whose ID does NOT start with this namespace prefix
46     */
47    public function exclude(PageSet $pages): PageSet
48    {
49        $result = array_filter(
50            $pages->getPages(),
51            fn($id) => !str_starts_with($id, $this->prefix),
52            ARRAY_FILTER_USE_KEY
53        );
54        return new PageSet($result);
55    }
56}
57