]> BookStack Code Mirror - bookstack/blobdiff - app/Search/SearchOptionSet.php
ZIP Imports: Added API examples, finished testing
[bookstack] / app / Search / SearchOptionSet.php
index a54b1d33a69be92580021b27044236fa24ec9178..bd5e5a5b222671a737f620ba9513fdf219655c25 100644 (file)
@@ -2,12 +2,17 @@
 
 namespace BookStack\Search;
 
+use BookStack\Search\Options\SearchOption;
+
+/**
+ * @template T of SearchOption
+ */
 class SearchOptionSet
 {
     /**
-     * @var SearchOption[]
+     * @var T[]
      */
-    public array $options = [];
+    protected array $options = [];
 
     public function __construct(array $options = [])
     {
@@ -22,7 +27,8 @@ class SearchOptionSet
     public function toValueMap(): array
     {
         $map = [];
-        foreach ($this->options as $key => $option) {
+        foreach ($this->options as $index => $option) {
+            $key = $option->getKey() ?? $index;
             $map[$key] = $option->value;
         }
         return $map;
@@ -35,22 +41,42 @@ class SearchOptionSet
 
     public function filterEmpty(): self
     {
-        $filteredOptions = array_filter($this->options, fn (SearchOption $option) => !empty($option->value));
+        $filteredOptions = array_values(array_filter($this->options, fn (SearchOption $option) => !empty($option->value)));
         return new self($filteredOptions);
     }
 
-    public static function fromValueArray(array $values): self
+    /**
+     * @param class-string<SearchOption> $class
+     */
+    public static function fromValueArray(array $values, string $class): self
     {
-        $options = array_map(fn($val) => new SearchOption($val), $values);
+        $options = array_map(fn($val) => new $class($val), $values);
         return new self($options);
     }
 
-    public static function fromMapArray(array $values): self
+    /**
+     * @return T[]
+     */
+    public function all(): array
     {
-        $options = [];
-        foreach ($values as $key => $value) {
-            $options[$key] = new SearchOption($value);
-        }
-        return new self($options);
+        return $this->options;
+    }
+
+    /**
+     * @return self<T>
+     */
+    public function negated(): self
+    {
+        $values = array_values(array_filter($this->options, fn (SearchOption $option) => $option->negated));
+        return new self($values);
+    }
+
+    /**
+     * @return self<T>
+     */
+    public function nonNegated(): self
+    {
+        $values = array_values(array_filter($this->options, fn (SearchOption $option) => !$option->negated));
+        return new self($values);
     }
 }