3 namespace BookStack\Util;
5 use Illuminate\Http\Request;
8 * Handled options commonly used for item lists within the system, providing a standard
9 * model for handling and validating sort, order and search options.
11 class SimpleListOptions
13 protected string $typeKey;
14 protected string $sort;
15 protected string $order;
16 protected string $search;
17 protected array $sortOptions = [];
19 public function __construct(string $typeKey, string $sort, string $order, string $search = '')
21 $this->typeKey = $typeKey;
23 $this->order = $order;
24 $this->search = $search;
28 * Create a new instance from the given request.
29 * Takes the item type (plural) that's used as a key for storing sort preferences.
31 public static function fromRequest(Request $request, string $typeKey, bool $sortDescDefault = false): self
33 $search = $request->get('search', '');
34 $sort = setting()->getForCurrentUser($typeKey . '_sort', '');
35 $order = setting()->getForCurrentUser($typeKey . '_sort_order', $sortDescDefault ? 'desc' : 'asc');
37 return new self($typeKey, $sort, $order, $search);
41 * Configure the valid sort options for this set of list options.
42 * Provided sort options must be an array, keyed by search properties
43 * with values being user-visible option labels.
44 * Returns current options for easy fluent usage during creation.
46 public function withSortOptions(array $sortOptions): self
48 $this->sortOptions = array_merge($this->sortOptions, $sortOptions);
54 * Get the current order option.
56 public function getOrder(): string
58 return strtolower($this->order) === 'desc' ? 'desc' : 'asc';
62 * Get the current sort option.
64 public function getSort(): string
66 $default = array_key_first($this->sortOptions) ?? 'name';
67 $sort = $this->sort ?: $default;
69 if (empty($this->sortOptions) || array_key_exists($sort, $this->sortOptions)) {
77 * Get the set search term.
79 public function getSearch(): string
85 * Get the data to append for pagination.
87 public function getPaginationAppends(): array
89 return ['search' => $this->search];
93 * Get the data required by the sort control view.
95 public function getSortControlData(): array
98 'options' => $this->sortOptions,
99 'order' => $this->getOrder(),
100 'sort' => $this->getSort(),
101 'type' => $this->typeKey,