xref: /dokuwiki/inc/Search/Query/NamespacePredicate.php (revision 9369b4a991666bc911474806b106d8958e79f4c1)
10b1bbbbbSAndreas Gohr<?php
20b1bbbbbSAndreas Gohr
30b1bbbbbSAndreas Gohrnamespace dokuwiki\Search\Query;
40b1bbbbbSAndreas Gohr
50b1bbbbbSAndreas Gohr/**
60b1bbbbbSAndreas Gohr * A namespace prefix used to filter pages by their ID
70b1bbbbbSAndreas Gohr *
80b1bbbbbSAndreas Gohr * The prefix always includes a trailing colon (e.g., "wiki:") to ensure
90b1bbbbbSAndreas Gohr * exact namespace matching — "wiki:" won't match "wikipedia:page".
100b1bbbbbSAndreas Gohr */
110b1bbbbbSAndreas Gohrclass NamespacePredicate implements StackEntry
120b1bbbbbSAndreas Gohr{
130b1bbbbbSAndreas Gohr    protected string $prefix;
140b1bbbbbSAndreas Gohr
150b1bbbbbSAndreas Gohr    /**
160b1bbbbbSAndreas Gohr     * @param string $prefix namespace prefix including trailing colon
170b1bbbbbSAndreas Gohr     */
180b1bbbbbSAndreas Gohr    public function __construct(string $prefix)
190b1bbbbbSAndreas Gohr    {
200b1bbbbbSAndreas Gohr        $this->prefix = $prefix;
210b1bbbbbSAndreas Gohr    }
220b1bbbbbSAndreas Gohr
230b1bbbbbSAndreas Gohr    /**
240b1bbbbbSAndreas Gohr     * @return string the namespace prefix
250b1bbbbbSAndreas Gohr     */
260b1bbbbbSAndreas Gohr    public function getPrefix(): string
270b1bbbbbSAndreas Gohr    {
280b1bbbbbSAndreas Gohr        return $this->prefix;
290b1bbbbbSAndreas Gohr    }
300b1bbbbbSAndreas Gohr
310b1bbbbbSAndreas Gohr    /**
320b1bbbbbSAndreas Gohr     * Keep only pages whose ID starts with this namespace prefix
330b1bbbbbSAndreas Gohr     */
340b1bbbbbSAndreas Gohr    public function filter(PageSet $pages): PageSet
350b1bbbbbSAndreas Gohr    {
36*9369b4a9SAndreas Gohr        $result = array_filter(
37*9369b4a9SAndreas Gohr            $pages->getPages(),
38*9369b4a9SAndreas Gohr            fn($id) => str_starts_with($id, $this->prefix),
39*9369b4a9SAndreas Gohr            ARRAY_FILTER_USE_KEY
40*9369b4a9SAndreas Gohr        );
410b1bbbbbSAndreas Gohr        return new PageSet($result);
420b1bbbbbSAndreas Gohr    }
430b1bbbbbSAndreas Gohr
440b1bbbbbSAndreas Gohr    /**
450b1bbbbbSAndreas Gohr     * Keep only pages whose ID does NOT start with this namespace prefix
460b1bbbbbSAndreas Gohr     */
470b1bbbbbSAndreas Gohr    public function exclude(PageSet $pages): PageSet
480b1bbbbbSAndreas Gohr    {
49*9369b4a9SAndreas Gohr        $result = array_filter(
50*9369b4a9SAndreas Gohr            $pages->getPages(),
51*9369b4a9SAndreas Gohr            fn($id) => !str_starts_with($id, $this->prefix),
52*9369b4a9SAndreas Gohr            ARRAY_FILTER_USE_KEY
53*9369b4a9SAndreas Gohr        );
540b1bbbbbSAndreas Gohr        return new PageSet($result);
550b1bbbbbSAndreas Gohr    }
560b1bbbbbSAndreas Gohr}
57