EdlpAjaxController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. namespace Drupal\edlp_ajax\Controller;
  3. use Drupal\Core\Controller\ControllerBase;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Drupal\Core\Url;
  6. use Drupal\Core\Language\LanguageInterface;
  7. use Drupal\menu_link_content\Entity\MenuLinkContent;
  8. use Drupal\Core\Datetime\DrupalDateTime;
  9. // use Symfony\Component\HttpFoundation\JsonResponse;
  10. use \Drupal\block\Entity\Block;
  11. use Drupal\Core\Cache\CacheableJsonResponse;
  12. use Drupal\Core\Cache\CacheableMetadata;
  13. use Drupal\core\render\RenderContext;
  14. class EdlpAjaxController extends ControllerBase {
  15. private function query() {
  16. $this->langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
  17. $entity = entity_load($this->entity_type, $this->id);
  18. if ($entity->hasTranslation($this->langcode)){
  19. $this->entity = $entity->getTranslation($this->langcode);
  20. }else{
  21. $this->entity = $entity;
  22. }
  23. if($this->entity){
  24. switch($this->entity_type){
  25. case 'node':
  26. $this->bundle = $this->entity->getType();
  27. $this->title = $this->entity->getTitle();
  28. break;
  29. case 'taxonomy_term':
  30. $this->bundle = $this->entity->bundle();
  31. $this->title = $this->entity->getName();
  32. break;
  33. default:
  34. $this->bundle = NULL;
  35. $this->title = '';
  36. }
  37. }
  38. }
  39. private function getProductionDatesAside(){
  40. $now = new DrupalDateTime('now');
  41. $now->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
  42. $future_dates_query = \Drupal::entityQuery('node')
  43. ->condition('status', 1)
  44. ->condition('type', 'evenement')
  45. ->condition('field_page_liee.target_id', $this->entity->id(), 'IN')
  46. ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
  47. ->sort('field_date');
  48. $future_nids = $future_dates_query->execute();
  49. $past_dates_query = \Drupal::entityQuery('node')
  50. ->condition('status', 1)
  51. ->condition('type', 'evenement')
  52. ->condition('field_page_liee.target_id', $this->entity->id(), 'IN')
  53. ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '<')
  54. ->sort('field_date', 'DESC');
  55. $past_nids = $past_dates_query->execute();
  56. if(count($future_nids) || count($past_nids)){
  57. $aside = array(
  58. '#type'=>'container',
  59. "#attributes"=>array(
  60. "class"=>['agenda']
  61. )
  62. );
  63. $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  64. if(count($future_nids)){
  65. $future_nodes = entity_load_multiple('node', $future_nids);
  66. $future_list = array (
  67. '#theme' => 'item_list',
  68. '#items' => [],
  69. );
  70. foreach($future_nodes as $node){
  71. $future_list['#items'][] = $node_view_builder->view($node, 'aside');
  72. }
  73. $aside['future_events'] = array(
  74. "#type"=>"container",
  75. "#attributes"=>array(
  76. "class"=>['future-events']
  77. ),
  78. "#markup"=>"<h3>" . t("Upcoming events") . "</h3>",
  79. "future_events"=>$future_list
  80. );
  81. }
  82. if(count($past_nids)){
  83. $past_nodes = entity_load_multiple('node', $past_nids);
  84. $past_list = array (
  85. '#theme' => 'item_list',
  86. '#items' => [],
  87. );
  88. foreach($past_nodes as $node){
  89. $past_list['#items'][] = $node_view_builder->view($node, 'aside');
  90. }
  91. $aside['past_events'] = array(
  92. "#type"=>"container",
  93. "#attributes"=>array(
  94. "class"=>['past-events']
  95. ),
  96. "#markup"=>"<h3>" . t("Past events") . "</h3>",
  97. "past_events"=>$past_list
  98. );
  99. }
  100. }else{
  101. $aside = null;
  102. }
  103. return $aside;
  104. }
  105. /**
  106. *
  107. * return a renderable array
  108. */
  109. private function getAside() {
  110. if($this->bundle == 'page'){
  111. $aside = $this->getProductionDatesAside();
  112. }else{
  113. $aside = null;
  114. }
  115. return $aside;
  116. }
  117. private function toRenderable(){
  118. $this->query();
  119. if($this->entity){
  120. return array(
  121. "#theme"=>'edlp_ajax',
  122. "#entity_type" => $this->entity_type,
  123. '#entity' => $this->entity,
  124. '#view_mode' => $this->viewmode,
  125. '#aside' => $this->getAside(),
  126. '#bundle' => $this->bundle,
  127. );
  128. }else{
  129. return array(
  130. '#markup'=>'404! '.$this->entity_type.' '.$this->id." not found!"
  131. );
  132. }
  133. }
  134. /**
  135. * Get entity as json through ajax.
  136. *
  137. * @return json
  138. */
  139. public function entityjson($entity_type, $id, $viewmode) {
  140. $this->entity_type = $entity_type;
  141. $this->id = $id;
  142. $this->viewmode = $viewmode;
  143. $renderable = $this->toRenderable();
  144. // $rendered = render($renderable);
  145. // We can't render directly the entity as it throw an exception with cachable data
  146. // see http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
  147. $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
  148. return render($renderable);
  149. });
  150. $title = $this->title;
  151. $title .= $this->viewmode != '' && $this->viewmode != 'default' ? ' | ' . $this->viewmode : '';
  152. $data = [
  153. 'date' => time(),
  154. 'id' => $this->id,
  155. 'title' => $title,
  156. 'view_mode' => $this->viewmode,
  157. 'bundle' => $this->bundle,
  158. 'entity_type' => $this->entity_type,
  159. 'rendered'=> $rendered,
  160. 'language' => $this->langcode
  161. ];
  162. // if content type page (productions) :
  163. // -- get the menu items and linked dates
  164. // -- get the linked documents for corpus map
  165. if($this->bundle == "page"){
  166. $menuLinkManager = \Drupal::service('plugin.manager.menu.link');
  167. $links = $menuLinkManager->loadLinksByRoute('entity.node.canonical', array('node' => $this->id), 'productions');
  168. // dpm($links, 'links');
  169. $menu_parents = array();
  170. foreach ($links as $link) {
  171. $parents = $menuLinkManager->getParentIds($link->getPluginId());
  172. // dpm($parents, 'parents');
  173. foreach ($parents as $parent_id) {
  174. $parent = $menuLinkManager->getInstance(array('id'=>$parent_id));
  175. // dpm($parent, 'parent');
  176. $url = $parent->getUrlObject();
  177. $sys_path = $url->getInternalPath();
  178. // dpm($sys_path);
  179. $menu_parents[] = $sys_path;
  180. }
  181. }
  182. $data['menu_parents'] = $menu_parents;
  183. // Documents liés
  184. $documents_lies = $this->entity->get('field_documents_lies')->getValue();
  185. if(count($documents_lies)){
  186. foreach ($documents_lies as $key => $field) {
  187. $data['documents_lies'][] = $field['target_id'];
  188. }
  189. }
  190. }
  191. // translations links
  192. $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, $this->entity->toUrl());
  193. if (isset($links->links)) {
  194. $translations_build = [
  195. '#theme' => 'links__language_block',
  196. '#links' => $links->links,
  197. '#attributes' => ['class' => ["language-switcher-{$links->method_id}"]],
  198. '#set_active_class' => TRUE,
  199. ];
  200. $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
  201. // dpm($links);
  202. $data['translations_links'] = $translations_rendered;
  203. }
  204. $data['#cache'] = [
  205. 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  206. 'tags' => [
  207. 'edlp-ajax-cache',
  208. // $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
  209. ],
  210. 'contexts' => [
  211. 'languages:language_content',
  212. 'user'
  213. ]
  214. ];
  215. // $response = new JsonResponse();
  216. // $response->setData($data);
  217. $response = new CacheableJsonResponse($data);
  218. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
  219. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
  220. return $response;
  221. // dpm($response);
  222. // return array(
  223. // '#markup'=>'hello'
  224. // );
  225. }
  226. /**
  227. * Get all visisble blocks from edlptheme as json through ajax.
  228. *
  229. * @return json
  230. */
  231. // NOT USED (YET)
  232. public function blocksjson($blockid) {
  233. $block_viewbuilder = \Drupal::entityTypeManager()->getViewBuilder('block');
  234. //
  235. $blocksids = [];
  236. if(!$blockid){
  237. // TODO: get all blocks definition from edlptheme
  238. $block_storage = \Drupal::entityTypeManager()->getStorage('block');
  239. // dpm($block_storage, '$block_storage');
  240. $allblocks = $block_storage->loadMultiple();
  241. // dpm($blocks, 'blocks');
  242. foreach ($allblocks as $block) {
  243. // dpm($block->id(), 'block');
  244. // dpm($block->getTheme(), 'theme');
  245. // $visibility = $block->getVisibility();
  246. if($block->getTheme() == "edlptheme"){
  247. // dpm($block, $block->id());
  248. $blocksids[] = $block->id();
  249. }
  250. }
  251. // $block_listbuilder = \Drupal::entityTypeManager()->getListBuilder('block');
  252. // dpm($block_listbuilder, '$block_listbuilder');
  253. // // foreach ($blocks as $key => $value) {
  254. // // $block = \Drupal\block\Entity\Block::load('productions');
  255. // // }
  256. }
  257. else{
  258. $blocksids[] = $blockid;
  259. }
  260. // dpm($blocksids, 'blockids');
  261. //
  262. $blocks = [];
  263. foreach ($blocksids as $id) {
  264. $block = Block::load($id);
  265. $block_render = $block_viewbuilder->view($block);
  266. $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($block_render) {
  267. return render($block_render);
  268. });
  269. $blocks[$id] = array(
  270. 'rendered'=> $rendered,
  271. 'region'=> str_replace('_', '-', $block->getRegion()),
  272. 'id'=> preg_replace('/^[^:]+:(.+)$/', 'block-$1', $block->getPluginId())
  273. );
  274. }
  275. // dpm($blocks, 'blocks');
  276. //
  277. $data = [
  278. 'blockid'=>$blockid,
  279. 'blocks' => $blocks,
  280. '#cache' => [
  281. 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
  282. 'tags' => [
  283. 'edlp-ajax-blocks-cache',
  284. // $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
  285. ]
  286. ]
  287. ];
  288. // dpm($data);
  289. //
  290. $response = new CacheableJsonResponse($data);
  291. // $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
  292. $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
  293. //
  294. return $response;
  295. // dpm($response);
  296. //
  297. return array(
  298. '#markup'=>'hello'
  299. );
  300. }
  301. }