Base.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. /**
  44. * get params from request
  45. */
  46. private function parseRequest(Request $request){
  47. // Get the typed string from the URL, if it exists.
  48. $this->keys = $request->query->get('keys');
  49. if($this->keys){
  50. $this->keys = Unicode::strtolower($this->keys);
  51. // $this->keys = Tags::explode($this->keys);
  52. \Drupal::logger('materio_sapi')->notice($this->keys);
  53. }
  54. $this->term = $request->query->get('term');
  55. $this->offset = $request->query->get('offset') ?? $this->offset;
  56. $this->limit = $request->query->get('limit') ?? $this->limit;
  57. }
  58. /**
  59. * Handler for ajax search.
  60. */
  61. public function getResults(Request $request) {
  62. $this->parseRequest($request);
  63. $resp = [
  64. 'keys' => $this->keys,
  65. 'term' => $this->term,
  66. 'range' => array(
  67. 'offset' => $this->offset,
  68. 'limit' => $this->limit
  69. ),
  70. ];
  71. if ($this->keys) {
  72. $this->sapiQuery();
  73. $resp['count'] = $this->results->getResultCount();
  74. $resp['infos'] = t('The search found @count result(s) with keywords @keys.', array(
  75. "@count" => $resp['count'],
  76. "@keys" => $this->keys
  77. ));
  78. $resp['options'] = $this->query->getOptions();
  79. // $items = [];
  80. $uuids = [];
  81. foreach ($this->results as $result) {
  82. // $nid = $result->getField('nid')->getValues()[0];
  83. // $uuid = $result->getField('uuid')->getValues()[0];
  84. // $title = $result->getField('title')->getValues()[0]->getText();
  85. // $items[] = [
  86. // 'nid' => $nid,
  87. // 'uuid' => $uuid,
  88. // 'title' => $title,
  89. // ];
  90. $uuids[] = $result->getField('uuid')->getValues()[0];
  91. }
  92. // $resp['items'] = $items;
  93. $resp['uuids'] = $uuids;
  94. }
  95. return new JsonResponse($resp);
  96. }
  97. /**
  98. * Handler for regular page search.
  99. */
  100. function pageHandler(Request $request){
  101. // \Drupal::logger('materio_sapi')->notice(print_r($request, true));
  102. $this->parseRequest($request);
  103. $resp = [
  104. "#title" => 'Base'
  105. ];
  106. if ($this->keys) {
  107. $resp['#title'] = $this->keys;
  108. $this->sapiQuery();
  109. $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  110. $items = $this->results->getResultItems();
  111. $this->items = [];
  112. foreach ($items as $item) {
  113. // \Drupal::logger('materio_sapi')->notice(print_r($item, true));
  114. try {
  115. /** @var \Drupal\Core\Entity\EntityInterface $entity */
  116. $entity = $item->getOriginalObject()->getValue();
  117. }
  118. catch (SearchApiException $e) {
  119. continue;
  120. }
  121. if (!$entity) {
  122. continue;
  123. }
  124. // TODO: define dynamicly viewmode
  125. $this->items[] = $node_view_builder->view($entity, 'teaser');
  126. }
  127. $resp['items'] = $this->items;
  128. }else{
  129. $resp['#markup'] = "no keys to search for";
  130. }
  131. return $resp;
  132. }
  133. }