2024-10-03 00:31:45 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\Search;
|
|
|
|
|
2024-10-03 22:59:50 +08:00
|
|
|
use BookStack\Search\Options\SearchOption;
|
|
|
|
|
2024-10-04 02:27:03 +08:00
|
|
|
/**
|
|
|
|
* @template T of SearchOption
|
|
|
|
*/
|
2024-10-03 00:31:45 +08:00
|
|
|
class SearchOptionSet
|
|
|
|
{
|
|
|
|
/**
|
2024-10-04 02:27:03 +08:00
|
|
|
* @var T[]
|
2024-10-03 00:31:45 +08:00
|
|
|
*/
|
2024-10-03 22:59:50 +08:00
|
|
|
protected array $options = [];
|
2024-10-03 00:31:45 +08:00
|
|
|
|
|
|
|
public function __construct(array $options = [])
|
|
|
|
{
|
|
|
|
$this->options = $options;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function toValueArray(): array
|
|
|
|
{
|
|
|
|
return array_map(fn(SearchOption $option) => $option->value, $this->options);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function toValueMap(): array
|
|
|
|
{
|
|
|
|
$map = [];
|
2024-10-03 22:59:50 +08:00
|
|
|
foreach ($this->options as $index => $option) {
|
|
|
|
$key = $option->getKey() ?? $index;
|
2024-10-03 00:31:45 +08:00
|
|
|
$map[$key] = $option->value;
|
|
|
|
}
|
|
|
|
return $map;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function merge(SearchOptionSet $set): self
|
|
|
|
{
|
|
|
|
return new self(array_merge($this->options, $set->options));
|
|
|
|
}
|
|
|
|
|
|
|
|
public function filterEmpty(): self
|
|
|
|
{
|
2024-10-03 22:59:50 +08:00
|
|
|
$filteredOptions = array_values(array_filter($this->options, fn (SearchOption $option) => !empty($option->value)));
|
2024-10-03 00:31:45 +08:00
|
|
|
return new self($filteredOptions);
|
|
|
|
}
|
|
|
|
|
2024-10-03 22:59:50 +08:00
|
|
|
/**
|
|
|
|
* @param class-string<SearchOption> $class
|
|
|
|
*/
|
|
|
|
public static function fromValueArray(array $values, string $class): self
|
2024-10-03 00:31:45 +08:00
|
|
|
{
|
2024-10-03 22:59:50 +08:00
|
|
|
$options = array_map(fn($val) => new $class($val), $values);
|
2024-10-03 00:31:45 +08:00
|
|
|
return new self($options);
|
|
|
|
}
|
|
|
|
|
2024-10-03 22:59:50 +08:00
|
|
|
/**
|
2024-10-04 02:27:03 +08:00
|
|
|
* @return T[]
|
2024-10-03 22:59:50 +08:00
|
|
|
*/
|
|
|
|
public function all(): array
|
2024-10-03 00:31:45 +08:00
|
|
|
{
|
2024-10-03 22:59:50 +08:00
|
|
|
return $this->options;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-10-04 02:27:03 +08:00
|
|
|
* @return T[]
|
2024-10-03 22:59:50 +08:00
|
|
|
*/
|
|
|
|
public function negated(): array
|
|
|
|
{
|
|
|
|
return array_values(array_filter($this->options, fn (SearchOption $option) => $option->negated));
|
2024-10-03 00:31:45 +08:00
|
|
|
}
|
|
|
|
}
|