Base.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. <?php
  2. // https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code
  3. namespace Drupal\materio_sapi\Controller;
  4. use Drupal\Core\Controller\ControllerBase;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Drupal\Component\Utility\Tags;
  8. use Drupal\Component\Utility\Unicode;
  9. use Drupal\search_api\Entity\Index;
  10. // https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
  11. /**
  12. * Defines a route controller for materio sapi search (regular and ajax).
  13. */
  14. class Base extends ControllerBase {
  15. private $limit = 15;
  16. private $offset = 0;
  17. private function sapiQuery(){
  18. $this->index = Index::load('database');
  19. $this->query = $this->index->query();
  20. // Change the parse mode for the search.
  21. $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  22. ->createInstance('direct');
  23. $parse_mode->setConjunction('OR');
  24. $this->query->setParseMode($parse_mode);
  25. // Set fulltext search keywords and fields.
  26. $this->query->keys($this->keys);
  27. // $this->query->setFulltextFields(['name']);
  28. // Set additional conditions.
  29. // $this->query->addCondition('status', 1)
  30. // ->addCondition('author', 1, '<>');
  31. // Restrict the search to specific languages.
  32. // $this->query->setLanguages(['de', 'it']);
  33. // Do paging.
  34. $this->query->range($this->offset, $this->limit);
  35. // Add sorting.
  36. $this->query->sort('search_api_relevance', 'DESC');
  37. // Set one or more tags for the query.
  38. // @see hook_search_api_query_TAG_alter()
  39. // @see hook_search_api_results_TAG_alter()
  40. $this->query->addTag('materio_sapi_search');
  41. $this->results = $this->query->execute();
  42. }
  43. private function defaultQuery(){
  44. $entity_storage = \Drupal::entityTypeManager()->getStorage('node');
  45. $this->query = $entity_storage->getQuery()
  46. ->condition('type', 'materiau')
  47. // ->condition('status', '1')
  48. ->range($this->offset, $this->limit)
  49. ->accessCheck(TRUE)
  50. ->sort('changed', 'DESC');
  51. // ->condition('field_example', 'test_value')
  52. $this->results = $this->query->execute();
  53. $this->count_query = $entity_storage->getQuery()
  54. ->condition('type', 'materiau')
  55. ->accessCheck(TRUE)
  56. // ->condition('status', '1')
  57. ->count();
  58. $this->count = $this->count_query->execute();
  59. }
  60. /**
  61. * get params from request
  62. */
  63. private function parseRequest(Request $request){
  64. // Get the typed string from the URL, if it exists.
  65. $this->keys = $request->query->get('keys');
  66. if($this->keys){
  67. $this->keys = Unicode::strtolower($this->keys);
  68. // $this->keys = Tags::explode($this->keys);
  69. \Drupal::logger('materio_sapi')->notice($this->keys);
  70. }
  71. $this->term = $request->query->get('term');
  72. $this->offset = $request->query->get('offset') ?? $this->offset;
  73. $this->limit = $request->query->get('limit') ?? $this->limit;
  74. }
  75. /**
  76. * Handler for ajax search.
  77. */
  78. public function getResults(Request $request) {
  79. $this->parseRequest($request);
  80. $resp = [
  81. 'range' => array(
  82. 'offset' => $this->offset,
  83. 'limit' => $this->limit
  84. ),
  85. ];
  86. if ($this->keys) {
  87. $this->sapiQuery();
  88. $resp['keys'] = $this->keys;
  89. $resp['term'] = $this->term;
  90. $resp['count'] = $this->results->getResultCount();
  91. $resp['infos'] = t('The search found @count result(s) with keywords @keys.', array(
  92. "@count" => $resp['count'],
  93. "@keys" => $this->keys
  94. ));
  95. $resp['options'] = $this->query->getOptions();
  96. // $items = [];
  97. $uuids = [];
  98. $nids = [];
  99. foreach ($this->results as $result) {
  100. // $nid = $result->getField('nid')->getValues()[0];
  101. // $uuid = $result->getField('uuid')->getValues()[0];
  102. // $title = $result->getField('title')->getValues()[0]->getText();
  103. // $items[] = [
  104. // 'nid' => $nid,
  105. // 'uuid' => $uuid,
  106. // 'title' => $title,
  107. // ];
  108. $uuids[] = $result->getField('uuid')->getValues()[0];
  109. $nids[] = $result->getField('nid')->getValues()[0];
  110. }
  111. // $resp['items'] = $items;
  112. $resp['uuids'] = $uuids;
  113. $resp['nids'] = $nids;
  114. } else {
  115. // no keys or terms to search for
  116. // display the default base page
  117. $this->defaultQuery();
  118. // $uuids = [];
  119. $nids = [];
  120. foreach ($this->results as $result) {
  121. // $uuids[] = $result->getField('uuid')->getValues()[0];
  122. $nids[] = $result;
  123. }
  124. // $resp['uuids'] = $uuids;
  125. $resp['nids'] = $nids;
  126. $resp['count'] = $this->count;
  127. $resp['infos'] = t('Please use the search form to search from our @count materials.', array(
  128. "@count" => $resp['count']
  129. ));
  130. }
  131. return new JsonResponse($resp);
  132. }
  133. /**
  134. * Handler for regular page search.
  135. */
  136. function pageHandler(Request $request){
  137. // \Drupal::logger('materio_sapi')->notice(print_r($request, true));
  138. $this->parseRequest($request);
  139. $resp = [
  140. "#title" => 'Base'
  141. ];
  142. if ($this->keys) {
  143. $resp['#title'] = $this->keys;
  144. $this->sapiQuery();
  145. $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  146. $items = $this->results->getResultItems();
  147. $this->items = [];
  148. foreach ($items as $item) {
  149. // \Drupal::logger('materio_sapi')->notice(print_r($item, true));
  150. try {
  151. /** @var \Drupal\Core\Entity\EntityInterface $entity */
  152. $entity = $item->getOriginalObject()->getValue();
  153. }
  154. catch (SearchApiException $e) {
  155. continue;
  156. }
  157. if (!$entity) {
  158. continue;
  159. }
  160. // TODO: define dynamicly viewmode
  161. $this->items[] = $node_view_builder->view($entity, 'teaser');
  162. }
  163. $resp['items'] = $this->items;
  164. }else{
  165. $resp['#markup'] = t("no keys to search for");
  166. }
  167. return $resp;
  168. }
  169. }