Base.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. // https://www.hashbangcode.com/article/drupal-8-date-search-boosting-search-api-and-solr-search
  20. // https://kgaut.net/blog/2018/drupal-8-search-api-effectuer-une-requete-dans-le-code.html
  21. $this->index = Index::load('database');
  22. // // get solarium fileds name
  23. // $solrFields = $this->index->getServerInstance()
  24. // ->getBackend()
  25. // ->getSolrFieldNames($this->index);
  26. //
  27. // // tag_tid"itm_tag_tid"
  28. // // thesaurus_tid"itm_thesaurus_tid"
  29. // $taxoSolrFieldsName = [];
  30. // foreach (['tag_tid', 'thesaurus_tid'] as $f) {
  31. // $taxoSolrFieldsName[] = $solrFields[$f];
  32. // }
  33. $this->query = $this->index->query();
  34. // Change the parse mode for the search.
  35. // Les différentes possibilités sont
  36. // - « direct » => Requête directe
  37. // - « terms » => Multiple words
  38. // - « phrase » => Single phrase
  39. // - " edismax " => ???
  40. $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  41. ->createInstance('direct');
  42. $parse_mode->setConjunction('OR');
  43. $this->query->setParseMode($parse_mode);
  44. // Set fulltext search keywords and fields.
  45. $this->query->keys($this->keys);
  46. // $this->query->setFulltextFields(['field_reference']);
  47. // Set additional conditions.
  48. // in case we search for material references like W0117
  49. if (preg_match_all('/[WTRPCMFGSO]\d{4}/i', $this->keys, $matches)) {
  50. $ref_conditions = $this->query->createConditionGroup('OR');
  51. foreach ($matches[0] as $key => $value) {
  52. $ref_conditions->addCondition('field_reference', $value);
  53. }
  54. $this->query->addConditionGroup($ref_conditions);
  55. }
  56. // in case of term id provided restrict the keys to taxo fields
  57. if ($this->term) {
  58. // $term_conditions = $this->query->createConditionGroup('OR');
  59. // $term = (int) $this->term;
  60. // foreach (['tag_tid', 'thesaurus_tid'] as $field) {
  61. // $term_conditions->addCondition($field, $term);
  62. // }
  63. // $this->query->addConditionGroup($term_conditions);
  64. // INSTEAD TRY TO BOOST TTHE TAG AND THESAURUS FIELDS
  65. // foreach ($taxoSolrFieldsName as $fname) {
  66. // // $solarium_query->addParam('bf', "recip(abs(ms(NOW,{$solrField})),3.16e-11,10,0.1)");
  67. // $bfparam = "if(gt(termfreq({$fname},{$this->term}),0),^21,0)";
  68. // $this->query->addParam('bf', $bfparam);
  69. // }
  70. $this->query->setOption('termid', $this->term);
  71. }
  72. // Restrict the search to specific languages.
  73. // $this->query->setLanguages(['de', 'it']);
  74. // Do paging.
  75. $this->query->range($this->offset, $this->limit);
  76. // Add sorting.
  77. $this->query->sort('search_api_relevance', 'DESC');
  78. // Set one or more tags for the query.
  79. // @see hook_search_api_query_TAG_alter()
  80. // @see hook_search_api_results_TAG_alter()
  81. $this->query->addTag('materio_sapi_search');
  82. $this->results = $this->query->execute();
  83. }
  84. private function defaultQuery(){
  85. $entity_storage = \Drupal::entityTypeManager()->getStorage('node');
  86. $this->query = $entity_storage->getQuery()
  87. ->condition('type', 'materiau')
  88. ->condition('status', '1')
  89. ->range($this->offset, $this->limit)
  90. ->accessCheck(TRUE)
  91. ->sort('changed', 'DESC');
  92. // ->condition('field_example', 'test_value')
  93. $this->results = $this->query->execute();
  94. $this->count_query = $entity_storage->getQuery()
  95. ->condition('type', 'materiau')
  96. ->accessCheck(TRUE)
  97. ->condition('status', '1')
  98. ->count();
  99. $this->count = $this->count_query->execute();
  100. }
  101. /**
  102. * get params from request
  103. */
  104. private function parseRequest(Request $request){
  105. // Get the typed string from the URL, if it exists.
  106. $this->keys = $request->query->get('keys');
  107. if($this->keys){
  108. $this->keys = Unicode::strtolower($this->keys);
  109. // $this->keys = Tags::explode($this->keys);
  110. \Drupal::logger('materio_sapi')->notice($this->keys);
  111. }
  112. $this->term = $request->query->get('term');
  113. $this->offset = $request->query->get('offset') ?? $this->offset;
  114. $this->limit = $request->query->get('limit') ?? $this->limit;
  115. }
  116. /**
  117. * Handler for ajax search.
  118. */
  119. public function getResults(Request $request) {
  120. $this->parseRequest($request);
  121. $resp = [
  122. 'range' => array(
  123. 'offset' => $this->offset,
  124. 'limit' => $this->limit
  125. ),
  126. ];
  127. if ($this->keys) {
  128. $this->sapiQuery();
  129. $resp['keys'] = $this->keys;
  130. $resp['term'] = $this->term;
  131. $resp['count'] = $this->results->getResultCount();
  132. $resp['infos'] = t('The search found @count result(s) with keywords @keys.', array(
  133. "@count" => $resp['count'],
  134. "@keys" => $this->keys
  135. ));
  136. $resp['options'] = $this->query->getOptions();
  137. // $items = [];
  138. $uuids = [];
  139. $nids = [];
  140. foreach ($this->results as $result) {
  141. // $nid = $result->getField('nid')->getValues()[0];
  142. // $uuid = $result->getField('uuid')->getValues()[0];
  143. // $title = $result->getField('title')->getValues()[0]->getText();
  144. // $items[] = [
  145. // 'nid' => $nid,
  146. // 'uuid' => $uuid,
  147. // 'title' => $title,
  148. // ];
  149. $uuids[] = $result->getField('uuid')->getValues()[0];
  150. $nids[] = $result->getField('nid')->getValues()[0];
  151. }
  152. // $resp['items'] = $items;
  153. $resp['uuids'] = $uuids;
  154. $resp['nids'] = $nids;
  155. } else {
  156. // no keys or terms to search for
  157. // display the default base page
  158. $this->defaultQuery();
  159. // $uuids = [];
  160. $nids = [];
  161. // Using entityTypeManager
  162. // Get a node storage object.
  163. $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  164. foreach ($this->results as $result) {
  165. $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  166. // Load a single node.
  167. $node = $node_storage->load($result);
  168. // check if has translation
  169. if ($node->hasTranslation($lang)) {
  170. // $uuids[] = $result->getField('uuid')->getValues()[0];
  171. $nids[] = $result;
  172. }
  173. }
  174. // $resp['uuids'] = $uuids;
  175. $resp['nids'] = $nids;
  176. $resp['count'] = $this->count;
  177. $resp['infos'] = t('Please use the search form to search from our @count materials.', array(
  178. "@count" => $resp['count']
  179. ));
  180. }
  181. return new JsonResponse($resp);
  182. }
  183. /**
  184. * Handler for regular page search.
  185. */
  186. function pageHandler(Request $request){
  187. // \Drupal::logger('materio_sapi')->notice(print_r($request, true));
  188. $this->parseRequest($request);
  189. $resp = [
  190. "#title" => 'Base'
  191. ];
  192. if ($this->keys) {
  193. $resp['#title'] = $this->keys;
  194. $this->sapiQuery();
  195. $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  196. $items = $this->results->getResultItems();
  197. $this->items = [];
  198. foreach ($items as $item) {
  199. // \Drupal::logger('materio_sapi')->notice(print_r($item, true));
  200. try {
  201. /** @var \Drupal\Core\Entity\EntityInterface $entity */
  202. $entity = $item->getOriginalObject()->getValue();
  203. }
  204. catch (SearchApiException $e) {
  205. continue;
  206. }
  207. if (!$entity) {
  208. continue;
  209. }
  210. // TODO: define dynamicly viewmode
  211. $this->items[] = $node_view_builder->view($entity, 'teaser');
  212. }
  213. $resp['items'] = $this->items;
  214. }else{
  215. $resp['#markup'] = t("no keys to search for");
  216. }
  217. return $resp;
  218. }
  219. }