Base.php 6.6 KB

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