CorpusController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. namespace Drupal\edlp_corpus\Controller;
  3. use Drupal\Core\Controller\ControllerBase;
  4. use Drupal\Core\Language\LanguageInterface;
  5. use Drupal\workflow\Entity\WorkflowManager;
  6. use Drupal\Core\Url;
  7. use Drupal\File\Entity\File;
  8. // use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Drupal\Core\Cache\CacheableJsonResponse;
  10. use Drupal\Core\Cache\CacheableMetadata;
  11. use Drupal\core\render\RenderContext;
  12. use Drupal\Core\Ajax\AjaxResponse;
  13. class CorpusController extends ControllerBase {
  14. /**
  15. * Display the markup.
  16. *
  17. * @return array
  18. */
  19. public function contentjson() {
  20. // @see https://www.droptica.com/blog/drupal-8-restjson-integration-simple-javascript-application/
  21. // @see https://www.sitepoint.com/drupal-8-version-entityfieldquery/
  22. // @see https://www.frobiovox.com/posts/2016/03/28/simplify-drupal-8-field-value-calls.html
  23. // @see https://chromatichq.com/blog/dependency-injection-drupal-8-plugins
  24. // Get a node storage object.
  25. // $file_storage = \Drupal::entityManager()->getStorage('node');
  26. $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  27. $config = \Drupal::config('system.site');
  28. $query = \Drupal::entityQuery('node')
  29. ->condition('status', 1)
  30. ->condition('type', 'enregistrement');
  31. $nids = $query->execute();
  32. $nodes = entity_load_multiple('node', $nids);
  33. $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  34. $nodes_data = [];
  35. foreach ($nodes as $node) {
  36. // this would be ideal but it's too heavy to load : the whole ajax json goes from 138kb to 1.23Md (even optimized)...
  37. // $node_builder = $view_builder->view($node, 'popup');
  38. // $node = $n->getTranslation($current_langcode);
  39. // remove masqué
  40. $sid = WorkflowManager::getCurrentStateId($node, 'field_workflow');
  41. if($sid != 'corpus_documents_publie') continue;
  42. $entrees = [];
  43. foreach ($node->get('field_entrees')->getValue() as $key => $term) {
  44. $entrees[] = $term['target_id'];
  45. }
  46. // remove if no entries
  47. if(!count($entrees)) continue;
  48. if ($node->hasTranslation($current_langcode)
  49. && !$node->getTranslation($current_langcode)->field_description->isEmpty()) {
  50. $description_values = $node->getTranslation($current_langcode)->get('field_description')->getValue();
  51. }else{
  52. $description_values = $node->get('field_description')->getValue();
  53. }
  54. $description = count($description_values) ? $description_values[0]['value'] : "";
  55. // dpm($description);
  56. $field_son_values = $node->get('field_son')->getValue();
  57. $audio_fid = count($field_son_values) ? $field_son_values[0]['target_id'] : "";
  58. $audio_file = \Drupal\file\Entity\File::load($audio_fid);
  59. $audio_url = null;
  60. // if node don't have a sound file atteched, skip it
  61. if(!$audio_file) continue;
  62. $son_uri = $audio_file->getFileUri();
  63. $audio_url = file_create_url($son_uri);
  64. // has article ?
  65. $article_value = $node->body->getValue();
  66. $has_article = count($article_value);
  67. // if($has_article && $article_value[0]['value'] == "")
  68. // dpm($article_value);
  69. $document_url = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($node, $current_langcode) {
  70. if ($node->hasTranslation($current_langcode)){
  71. return $node->getTranslation($current_langcode)->toUrl()->toString();
  72. }else{
  73. return $node->toUrl()->toString();
  74. }
  75. });
  76. // favoris marker
  77. $nodes_data[] = array(
  78. "nid" => $node->get('nid')->getString(),
  79. "title" => $node->get('title')->getString(),
  80. "description" => $description,
  81. "entrees" => $entrees,
  82. // "son_fid" => $audio_fid,
  83. "audio_url" => $audio_url,
  84. "has_article" => $has_article,
  85. "chutier_action" => 'add',
  86. "document_url" => $document_url,
  87. );
  88. }
  89. $query = \Drupal::entityQuery('taxonomy_term')
  90. ->condition('vid', 'entrees');
  91. $tids = $query->execute();
  92. // $nodes = entity_load_multiple('node', $nids);
  93. foreach ($tids as $tid) {
  94. $entrees[] = $tid;
  95. }
  96. $data = array(
  97. 'date' => time(),
  98. 'site_name' => $config->get('name'),
  99. 'count' => count($nodes),
  100. 'nodes' => $nodes_data,
  101. 'entrees' => $entrees,
  102. 'language' => $current_langcode,
  103. );
  104. // https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/
  105. // cache is invalidated in edlp_corpus.module by tags
  106. $data['#cache'] = [
  107. 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  108. 'tags' => ['rebuild-corpus-cache'],
  109. 'contexts' => ['languages:language_content'],
  110. ];
  111. // $response = new JsonResponse();
  112. // $response->setData($data);
  113. $response = new CacheableJsonResponse($data);
  114. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
  115. return $response;
  116. return array(
  117. '#markup'=>'Hello Corpus'
  118. );
  119. }
  120. // _ _ _
  121. // | | __ _ __| |_ __| |___ __ ___
  122. // | |__/ _` (_-< _/ _` / _ \/ _(_-<
  123. // |____\__,_/__/\__\__,_\___/\__/__/
  124. private function query() {
  125. $query = \Drupal::entityQuery('node')
  126. ->condition('status', 1)
  127. ->condition('type', 'enregistrement')
  128. ->sort('created', 'DESC')
  129. ->range(0,20);
  130. $nids = $query->execute();
  131. $this->lastdocs_nodes = entity_load_multiple('node', $nids);
  132. // record an array of nids for corpus map filtering
  133. $this->lastdocs_nids = [];
  134. foreach($nids as $key => $nid){
  135. $this->lastdocs_nids[] = $nid;
  136. }
  137. }
  138. private function toRenderable(){
  139. $this->query();
  140. // dpm($this->next_event_node);
  141. return array(
  142. "#theme"=>'edlp_corpus_lastdocs',
  143. '#lastdocs_nodes' => $this->lastdocs_nodes
  144. );
  145. }
  146. /**
  147. * Display lastdocs as a page.
  148. *
  149. * @return renderable array
  150. */
  151. public function lastdocs() {
  152. return $this->toRenderable();
  153. }
  154. /**
  155. * Get lastdocs data as json through ajax.
  156. *
  157. * @return json
  158. */
  159. public function lastdocsjson() {
  160. $renderable = $this->toRenderable();
  161. // $rendered = render($renderable);
  162. // We can't render directly the entity as it throw an exception with cachable data
  163. //http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
  164. $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
  165. return render($renderable);
  166. });
  167. $data = [
  168. 'rendered'=> $rendered,
  169. 'title'=>'Last Documents',
  170. 'documents_lies' => $this->lastdocs_nids,
  171. ];
  172. // translations links
  173. // use Drupal\Core\Url;
  174. // use Drupal\Core\Language\LanguageInterface;
  175. $route_name = 'edlp_corpus.lastdocs';
  176. $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
  177. if (isset($links->links)) {
  178. $translations_build = [
  179. '#theme' => 'links__language_block',
  180. '#links' => $links->links,
  181. '#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
  182. '#set_active_class' => TRUE,
  183. ];
  184. $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
  185. $data['translations_links'] = $translations_rendered;
  186. }
  187. $data['#cache'] = [
  188. 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  189. 'tags' => ['edlp-lastdocs-cache']
  190. ];
  191. // $response = new JsonResponse();
  192. // $response->setData($data);
  193. $response = new CacheableJsonResponse($data);
  194. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
  195. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
  196. return $response;
  197. }
  198. // _ _ _ _ ___ _
  199. // /_\ _ _| |_(_)__| |___ ___ |_ _|_ _ __| |_____ __
  200. // / _ \| '_| _| / _| / -_|_-< | || ' \/ _` / -_) \ /
  201. // /_/ \_\_| \__|_\__|_\___/__/ |___|_||_\__,_\___/_\_\
  202. private function articlesQuery() {
  203. $query = \Drupal::entityQuery('node')
  204. ->condition('status', 1)
  205. ->condition('type', 'enregistrement')
  206. ->condition('body', '', "<>")
  207. ->sort('created', 'DESC')
  208. ->range(0,20);
  209. $nids = $query->execute();
  210. $nodes = entity_load_multiple('node', $nids);
  211. $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  212. $this->articles_nodes = [];
  213. $this->articles_nids = [];
  214. foreach ($nodes as $node) {
  215. // remove masqué
  216. $sid = WorkflowManager::getCurrentStateId($node, 'field_workflow');
  217. if($sid != 'corpus_documents_publie') continue;
  218. // TODO: check if article is translated
  219. if (!$node->hasTranslation($current_langcode)
  220. || $node->getTranslation($current_langcode)->body->isEmpty()) continue;
  221. $this->articles_nodes[] = $node;
  222. // record an array of nids for corpus map filtering
  223. $this->articles_nids[] = $node->get('nid')->getString();
  224. }
  225. }
  226. private function articlesToRenderable(){
  227. $this->articlesQuery();
  228. // dpm($this->next_event_node);
  229. return array(
  230. "#theme"=>'edlp_corpus_articlesindex',
  231. '#articles_nodes' => $this->articles_nodes
  232. );
  233. }
  234. /**
  235. * Display lastdocs as a page.
  236. *
  237. * @return renderable array
  238. */
  239. public function articlesindex() {
  240. return $this->articlesToRenderable();
  241. }
  242. /**
  243. * Get lastdocs data as json through ajax.
  244. *
  245. * @return json
  246. */
  247. public function articlesindexjson() {
  248. $renderable = $this->articlesToRenderable();
  249. // $rendered = render($renderable);
  250. // We can't render directly the entity as it throw an exception with cachable data
  251. //http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
  252. $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
  253. return render($renderable);
  254. });
  255. $data = [
  256. 'rendered'=> $rendered,
  257. 'title'=>'Articles',
  258. 'articles' => $this->articles_nids,
  259. 'documents_lies' => $this->articles_nids,
  260. ];
  261. // translations links
  262. // use Drupal\Core\Url;
  263. // use Drupal\Core\Language\LanguageInterface;
  264. $route_name = 'edlp_corpus.articlesindex';
  265. $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
  266. if (isset($links->links)) {
  267. $translations_build = [
  268. '#theme' => 'links__language_block',
  269. '#links' => $links->links,
  270. '#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
  271. '#set_active_class' => TRUE,
  272. ];
  273. $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
  274. $data['translations_links'] = $translations_rendered;
  275. }
  276. $data['#cache'] = [
  277. 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  278. 'tags' => ['edlp-articlesindex-cache']
  279. ];
  280. // $response = new JsonResponse();
  281. // $response->setData($data);
  282. $response = new CacheableJsonResponse($data);
  283. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
  284. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
  285. return $response;
  286. }
  287. }