]> BookStack Code Mirror - bookstack/blob - app/Sorting/SortUrl.php
Comments: Moved to tab UI, Converted tabs component to ts
[bookstack] / app / Sorting / SortUrl.php
1 <?php
2
3 namespace BookStack\Sorting;
4
5 /**
6  * Generate a URL with multiple parameters for sorting purposes.
7  * Works out the logic to set the correct sorting direction
8  * Discards empty parameters and allows overriding.
9  */
10 class SortUrl
11 {
12     public function __construct(
13         protected string $path,
14         protected array $data,
15         protected array $overrideData = []
16     ) {
17     }
18
19     public function withOverrideData(array $overrideData = []): self
20     {
21         return new self($this->path, $this->data, $overrideData);
22     }
23
24     public function build(): string
25     {
26         $queryStringSections = [];
27         $queryData = array_merge($this->data, $this->overrideData);
28
29         // Change sorting direction if already sorted on current attribute
30         if (isset($this->overrideData['sort']) && $this->overrideData['sort'] === $this->data['sort']) {
31             $queryData['order'] = ($this->data['order'] === 'asc') ? 'desc' : 'asc';
32         } elseif (isset($this->overrideData['sort'])) {
33             $queryData['order'] = 'asc';
34         }
35
36         foreach ($queryData as $name => $value) {
37             $trimmedVal = trim($value);
38             if ($trimmedVal !== '') {
39                 $queryStringSections[] = urlencode($name) . '=' . urlencode($trimmedVal);
40             }
41         }
42
43         if (count($queryStringSections) === 0) {
44             return url($this->path);
45         }
46
47         return url($this->path . '?' . implode('&', $queryStringSections));
48     }
49 }