ac078e18eb5393ffa78c0b46cb798fc40343e879
[yaffs-website] / web / core / modules / search / src / Controller / SearchController.php
1 <?php
2
3 namespace Drupal\search\Controller;
4
5 use Drupal\Core\Cache\CacheableDependencyInterface;
6 use Drupal\Core\Controller\ControllerBase;
7 use Drupal\Core\Render\RendererInterface;
8 use Drupal\search\SearchPageInterface;
9 use Drupal\search\SearchPageRepositoryInterface;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11 use Symfony\Component\HttpFoundation\Request;
12
13 /**
14  * Route controller for search.
15  */
16 class SearchController extends ControllerBase {
17
18   /**
19    * The search page repository.
20    *
21    * @var \Drupal\search\SearchPageRepositoryInterface
22    */
23   protected $searchPageRepository;
24
25   /**
26    * A logger instance.
27    *
28    * @var \Psr\Log\LoggerInterface
29    */
30   protected $logger;
31
32   /**
33    * The renderer.
34    *
35    * @var \Drupal\Core\Render\RendererInterface
36    */
37   protected $renderer;
38
39   /**
40    * Constructs a new search controller.
41    *
42    * @param \Drupal\search\SearchPageRepositoryInterface $search_page_repository
43    *   The search page repository.
44    * @param \Drupal\Core\Render\RendererInterface $renderer
45    *   The renderer.
46    */
47   public function __construct(SearchPageRepositoryInterface $search_page_repository, RendererInterface $renderer) {
48     $this->searchPageRepository = $search_page_repository;
49     $this->logger = $this->getLogger('search');
50     $this->renderer = $renderer;
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   public static function create(ContainerInterface $container) {
57     return new static(
58       $container->get('search.search_page_repository'),
59       $container->get('renderer')
60     );
61   }
62
63   /**
64    * Creates a render array for the search page.
65    *
66    * @param \Symfony\Component\HttpFoundation\Request $request
67    *   The request object.
68    * @param \Drupal\search\SearchPageInterface $entity
69    *   The search page entity.
70    *
71    * @return array
72    *   The search form and search results build array.
73    */
74   public function view(Request $request, SearchPageInterface $entity) {
75     $build = [];
76     $plugin = $entity->getPlugin();
77
78     // Build the form first, because it may redirect during the submit,
79     // and we don't want to build the results based on last time's request.
80     $build['#cache']['contexts'][] = 'url.query_args:keys';
81     if ($request->query->has('keys')) {
82       $keys = trim($request->query->get('keys'));
83       $plugin->setSearch($keys, $request->query->all(), $request->attributes->all());
84     }
85
86     $build['#title'] = $plugin->suggestedTitle();
87     $build['search_form'] = $this->entityFormBuilder()->getForm($entity, 'search');
88
89     // Build search results, if keywords or other search parameters are in the
90     // GET parameters. Note that we need to try the search if 'keys' is in
91     // there at all, vs. being empty, due to advanced search.
92     $results = [];
93     if ($request->query->has('keys')) {
94       if ($plugin->isSearchExecutable()) {
95         // Log the search.
96         if ($this->config('search.settings')->get('logging')) {
97           $this->logger->notice('Searched %type for %keys.', ['%keys' => $keys, '%type' => $entity->label()]);
98         }
99
100         // Collect the search results.
101         $results = $plugin->buildResults();
102       }
103       else {
104         // The search not being executable means that no keywords or other
105         // conditions were entered.
106         drupal_set_message($this->t('Please enter some keywords.'), 'error');
107       }
108     }
109
110     if (count($results)) {
111       $build['search_results_title'] = [
112         '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
113       ];
114     }
115
116     $build['search_results'] = [
117       '#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],
118       '#items' => $results,
119       '#empty' => [
120         '#markup' => '<h3>' . $this->t('Your search yielded no results.') . '</h3>',
121       ],
122       '#list_type' => 'ol',
123       '#context' => [
124         'plugin' => $plugin->getPluginId(),
125       ],
126     ];
127
128     $this->renderer->addCacheableDependency($build, $entity);
129     if ($plugin instanceof CacheableDependencyInterface) {
130       $this->renderer->addCacheableDependency($build, $plugin);
131     }
132
133     // If this plugin uses a search index, then also add the cache tag tracking
134     // that search index, so that cached search result pages are invalidated
135     // when necessary.
136     if ($plugin->getType()) {
137       $build['search_results']['#cache']['tags'][] = 'search_index';
138       $build['search_results']['#cache']['tags'][] = 'search_index:' . $plugin->getType();
139     }
140
141     $build['pager'] = [
142       '#type' => 'pager',
143     ];
144
145     return $build;
146   }
147
148   /**
149    * Creates a render array for the search help page.
150    *
151    * @param \Symfony\Component\HttpFoundation\Request $request
152    *   The request object.
153    * @param \Drupal\search\SearchPageInterface $entity
154    *   The search page entity.
155    *
156    * @return array
157    *   The search help page.
158    */
159   public function searchHelp(SearchPageInterface $entity) {
160     $build = [];
161
162     $build['search_help'] = $entity->getPlugin()->getHelp();
163
164     return $build;
165   }
166
167   /**
168    * Redirects to a search page.
169    *
170    * This is used to redirect from /search to the default search page.
171    *
172    * @param \Drupal\search\SearchPageInterface $entity
173    *   The search page entity.
174    *
175    * @return \Symfony\Component\HttpFoundation\RedirectResponse
176    *   A redirect to the search page.
177    */
178   public function redirectSearchPage(SearchPageInterface $entity) {
179     return $this->redirect('search.view_' . $entity->id());
180   }
181
182   /**
183    * Route title callback.
184    *
185    * @param \Drupal\search\SearchPageInterface $search_page
186    *   The search page entity.
187    *
188    * @return string
189    *   The title for the search page edit form.
190    */
191   public function editTitle(SearchPageInterface $search_page) {
192     return $this->t('Edit %label search page', ['%label' => $search_page->label()]);
193   }
194
195   /**
196    * Performs an operation on the search page entity.
197    *
198    * @param \Drupal\search\SearchPageInterface $search_page
199    *   The search page entity.
200    * @param string $op
201    *   The operation to perform, usually 'enable' or 'disable'.
202    *
203    * @return \Symfony\Component\HttpFoundation\RedirectResponse
204    *   A redirect back to the search settings page.
205    */
206   public function performOperation(SearchPageInterface $search_page, $op) {
207     $search_page->$op()->save();
208
209     if ($op == 'enable') {
210       drupal_set_message($this->t('The %label search page has been enabled.', ['%label' => $search_page->label()]));
211     }
212     elseif ($op == 'disable') {
213       drupal_set_message($this->t('The %label search page has been disabled.', ['%label' => $search_page->label()]));
214     }
215
216     $url = $search_page->urlInfo('collection');
217     return $this->redirect($url->getRouteName(), $url->getRouteParameters(), $url->getOptions());
218   }
219
220   /**
221    * Sets the search page as the default.
222    *
223    * @param \Drupal\search\SearchPageInterface $search_page
224    *   The search page entity.
225    *
226    * @return \Symfony\Component\HttpFoundation\RedirectResponse
227    *   A redirect to the search settings page.
228    */
229   public function setAsDefault(SearchPageInterface $search_page) {
230     // Set the default page to this search page.
231     $this->searchPageRepository->setDefaultSearchPage($search_page);
232
233     drupal_set_message($this->t('The default search page is now %label. Be sure to check the ordering of your search pages.', ['%label' => $search_page->label()]));
234     return $this->redirect('entity.search_page.collection');
235   }
236
237 }