]>
Commit | Line | Data |
---|---|---|
03340c18 A |
1 | <?php |
2 | ||
3 | declare(strict_types=1); | |
4 | ||
5 | namespace Shaarli\Front\Controller; | |
6 | ||
7 | use Slim\Http\Request; | |
8 | use Slim\Http\Response; | |
9 | ||
10 | /** | |
11 | * Class TagController | |
12 | * | |
13 | * Slim controller handle tags. | |
14 | * | |
15 | * @package Front\Controller | |
16 | */ | |
17 | class TagController extends ShaarliController | |
18 | { | |
19 | /** | |
20 | * Add another tag in the current search through an HTTP redirection. | |
21 | * | |
22 | * @param array $args Should contain `newTag` key as tag to add to current search | |
23 | */ | |
24 | public function addTag(Request $request, Response $response, array $args): Response | |
25 | { | |
26 | $newTag = $args['newTag'] ?? null; | |
27 | $referer = $this->container->environment['HTTP_REFERER'] ?? null; | |
28 | ||
29 | // In case browser does not send HTTP_REFERER, we search a single tag | |
30 | if (null === $referer) { | |
31 | if (null !== $newTag) { | |
32 | return $response->withRedirect('./?searchtags='. urlencode($newTag)); | |
33 | } | |
34 | ||
35 | return $response->withRedirect('./'); | |
36 | } | |
37 | ||
38 | $currentUrl = parse_url($this->container->environment['HTTP_REFERER']); | |
39 | parse_str($currentUrl['query'] ?? '', $params); | |
40 | ||
41 | if (null === $newTag) { | |
42 | return $response->withRedirect(($currentUrl['path'] ?? './') .'?'. http_build_query($params)); | |
43 | } | |
44 | ||
45 | // Prevent redirection loop | |
46 | if (isset($params['addtag'])) { | |
47 | unset($params['addtag']); | |
48 | } | |
49 | ||
50 | // Check if this tag is already in the search query and ignore it if it is. | |
51 | // Each tag is always separated by a space | |
52 | $currentTags = isset($params['searchtags']) ? explode(' ', $params['searchtags']) : []; | |
53 | ||
54 | $addtag = true; | |
55 | foreach ($currentTags as $value) { | |
56 | if ($value === $newTag) { | |
57 | $addtag = false; | |
58 | break; | |
59 | } | |
60 | } | |
61 | ||
62 | // Append the tag if necessary | |
63 | if (true === $addtag) { | |
64 | $currentTags[] = trim($newTag); | |
65 | } | |
66 | ||
67 | $params['searchtags'] = trim(implode(' ', $currentTags)); | |
68 | ||
69 | // We also remove page (keeping the same page has no sense, since the results are different) | |
70 | unset($params['page']); | |
71 | ||
72 | return $response->withRedirect(($currentUrl['path'] ?? './') .'?'. http_build_query($params)); | |
73 | } | |
74 | } |