Base.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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(['field_reference']);
  28. // Set additional conditions.
  29. // in case we search for material reference like W0117
  30. if (preg_match('/^[WTRPCMFGSO]\d{4}$/i', $this->keys, $matches)) {
  31. $this->query->addCondition('field_reference', $this->keys);
  32. }
  33. // Restrict the search to specific languages.
  34. // $this->query->setLanguages(['de', 'it']);
  35. // Do paging.
  36. $this->query->range($this->offset, $this->limit);
  37. // Add sorting.
  38. $this->query->sort('search_api_relevance', 'DESC');
  39. // Set one or more tags for the query.
  40. // @see hook_search_api_query_TAG_alter()
  41. // @see hook_search_api_results_TAG_alter()
  42. $this->query->addTag('materio_sapi_search');
  43. $this->results = $this->query->execute();
  44. }
  45. private function defaultQuery(){
  46. $entity_storage = \Drupal::entityTypeManager()->getStorage('node');
  47. $this->query = $entity_storage->getQuery()
  48. ->condition('type', 'materiau')
  49. ->condition('status', '1')
  50. ->range($this->offset, $this->limit)
  51. ->accessCheck(TRUE)
  52. ->sort('changed', 'DESC');
  53. // ->condition('field_example', 'test_value')
  54. $this->results = $this->query->execute();
  55. $this->count_query = $entity_storage->getQuery()
  56. ->condition('type', 'materiau')
  57. ->accessCheck(TRUE)
  58. ->condition('status', '1')
  59. ->count();
  60. $this->count = $this->count_query->execute();
  61. }
  62. /**
  63. * get params from request
  64. */
  65. private function parseRequest(Request $request){
  66. // Get the typed string from the URL, if it exists.
  67. $this->keys = $request->query->get('keys');
  68. if($this->keys){
  69. $this->keys = Unicode::strtolower($this->keys);
  70. // $this->keys = Tags::explode($this->keys);
  71. \Drupal::logger('materio_sapi')->notice($this->keys);
  72. }
  73. $this->term = $request->query->get('term');
  74. $this->offset = $request->query->get('offset') ?? $this->offset;
  75. $this->limit = $request->query->get('limit') ?? $this->limit;
  76. }
  77. /**
  78. * Handler for ajax search.
  79. */
  80. public function getResults(Request $request) {
  81. $this->parseRequest($request);
  82. $resp = [
  83. 'range' => array(
  84. 'offset' => $this->offset,
  85. 'limit' => $this->limit
  86. ),
  87. ];
  88. if ($this->keys) {
  89. $this->sapiQuery();
  90. $resp['keys'] = $this->keys;
  91. $resp['term'] = $this->term;
  92. $resp['count'] = $this->results->getResultCount();
  93. $resp['infos'] = t('The search found @count result(s) with keywords @keys.', array(
  94. "@count" => $resp['count'],
  95. "@keys" => $this->keys
  96. ));
  97. $resp['options'] = $this->query->getOptions();
  98. // $items = [];
  99. $uuids = [];
  100. $nids = [];
  101. foreach ($this->results as $result) {
  102. // $nid = $result->getField('nid')->getValues()[0];
  103. // $uuid = $result->getField('uuid')->getValues()[0];
  104. // $title = $result->getField('title')->getValues()[0]->getText();
  105. // $items[] = [
  106. // 'nid' => $nid,
  107. // 'uuid' => $uuid,
  108. // 'title' => $title,
  109. // ];
  110. $uuids[] = $result->getField('uuid')->getValues()[0];
  111. $nids[] = $result->getField('nid')->getValues()[0];
  112. }
  113. // $resp['items'] = $items;
  114. $resp['uuids'] = $uuids;
  115. $resp['nids'] = $nids;
  116. } else {
  117. // no keys or terms to search for
  118. // display the default base page
  119. $this->defaultQuery();
  120. // $uuids = [];
  121. $nids = [];
  122. // Using entityTypeManager
  123. // Get a node storage object.
  124. $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  125. foreach ($this->results as $result) {
  126. $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  127. // Load a single node.
  128. $node = $node_storage->load($result);
  129. // check if has translation
  130. if ($node->hasTranslation($lang)) {
  131. // $uuids[] = $result->getField('uuid')->getValues()[0];
  132. $nids[] = $result;
  133. }
  134. }
  135. // $resp['uuids'] = $uuids;
  136. $resp['nids'] = $nids;
  137. $resp['count'] = $this->count;
  138. $resp['infos'] = t('Please use the search form to search from our @count materials.', array(
  139. "@count" => $resp['count']
  140. ));
  141. }
  142. return new JsonResponse($resp);
  143. }
  144. /**
  145. * Handler for regular page search.
  146. */
  147. function pageHandler(Request $request){
  148. // \Drupal::logger('materio_sapi')->notice(print_r($request, true));
  149. $this->parseRequest($request);
  150. $resp = [
  151. "#title" => 'Base'
  152. ];
  153. if ($this->keys) {
  154. $resp['#title'] = $this->keys;
  155. $this->sapiQuery();
  156. $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  157. $items = $this->results->getResultItems();
  158. $this->items = [];
  159. foreach ($items as $item) {
  160. // \Drupal::logger('materio_sapi')->notice(print_r($item, true));
  161. try {
  162. /** @var \Drupal\Core\Entity\EntityInterface $entity */
  163. $entity = $item->getOriginalObject()->getValue();
  164. }
  165. catch (SearchApiException $e) {
  166. continue;
  167. }
  168. if (!$entity) {
  169. continue;
  170. }
  171. // TODO: define dynamicly viewmode
  172. $this->items[] = $node_view_builder->view($entity, 'teaser');
  173. }
  174. $resp['items'] = $this->items;
  175. }else{
  176. $resp['#markup'] = t("no keys to search for");
  177. }
  178. return $resp;
  179. }
  180. }