123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357 |
- <?php
- namespace Drupal\edlp_corpus\Controller;
- use Drupal\Core\Controller\ControllerBase;
- use Drupal\Core\Language\LanguageInterface;
- use Drupal\workflow\Entity\WorkflowManager;
- use Drupal\Core\Url;
- use Drupal\File\Entity\File;
- // use Symfony\Component\HttpFoundation\JsonResponse;
- use Drupal\Core\Cache\CacheableJsonResponse;
- use Drupal\Core\Cache\CacheableMetadata;
- use Drupal\core\render\RenderContext;
- use Drupal\Core\Ajax\AjaxResponse;
- class CorpusController extends ControllerBase {
- /**
- * Display the markup.
- *
- * @return array
- */
- public function contentjson() {
- // @see https://www.droptica.com/blog/drupal-8-restjson-integration-simple-javascript-application/
- // @see https://www.sitepoint.com/drupal-8-version-entityfieldquery/
- // @see https://www.frobiovox.com/posts/2016/03/28/simplify-drupal-8-field-value-calls.html
- // @see https://chromatichq.com/blog/dependency-injection-drupal-8-plugins
- // Get a node storage object.
- // $file_storage = \Drupal::entityManager()->getStorage('node');
- $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $config = \Drupal::config('system.site');
- $query = \Drupal::entityQuery('node')
- ->condition('status', 1)
- ->condition('type', 'enregistrement');
- $nids = $query->execute();
- $nodes = entity_load_multiple('node', $nids);
- $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
- $nodes_data = [];
- foreach ($nodes as $node) {
- // this would be ideal but it's too heavy to load : the whole ajax json goes from 138kb to 1.23Md (even optimized)...
- // $node_builder = $view_builder->view($node, 'popup');
- // $node = $n->getTranslation($current_langcode);
- // remove masqué
- $sid = WorkflowManager::getCurrentStateId($node, 'field_workflow');
- if($sid != 'corpus_documents_publie') continue;
- $entrees = [];
- foreach ($node->get('field_entrees')->getValue() as $key => $term) {
- $entrees[] = $term['target_id'];
- }
- // remove if no entries
- if(!count($entrees)) continue;
- if ($node->hasTranslation($current_langcode)
- && !$node->getTranslation($current_langcode)->field_description->isEmpty()) {
- $description_values = $node->getTranslation($current_langcode)->get('field_description')->getValue();
- }else{
- $description_values = $node->get('field_description')->getValue();
- }
- $description = count($description_values) ? $description_values[0]['value'] : "";
- // dpm($description);
- $field_son_values = $node->get('field_son')->getValue();
- $audio_fid = count($field_son_values) ? $field_son_values[0]['target_id'] : "";
- $audio_file = \Drupal\file\Entity\File::load($audio_fid);
- $audio_url = null;
- // if node don't have a sound file atteched, skip it
- if(!$audio_file) continue;
- $son_uri = $audio_file->getFileUri();
- $audio_url = file_create_url($son_uri);
- // has article ?
- $article_value = $node->body->getValue();
- $has_article = count($article_value);
- // if($has_article && $article_value[0]['value'] == "")
- // dpm($article_value);
- $document_url = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($node, $current_langcode) {
- if ($node->hasTranslation($current_langcode)){
- return $node->getTranslation($current_langcode)->toUrl()->toString();
- }else{
- return $node->toUrl()->toString();
- }
- });
- // favoris marker
- $nodes_data[] = array(
- "nid" => $node->get('nid')->getString(),
- "title" => $node->get('title')->getString(),
- "description" => $description,
- "entrees" => $entrees,
- // "son_fid" => $audio_fid,
- "audio_url" => $audio_url,
- "has_article" => $has_article,
- "chutier_action" => 'add',
- "document_url" => $document_url,
- );
- }
- $query = \Drupal::entityQuery('taxonomy_term')
- ->condition('vid', 'entrees');
- $tids = $query->execute();
- // $nodes = entity_load_multiple('node', $nids);
- foreach ($tids as $tid) {
- $entrees[] = $tid;
- }
- $data = array(
- 'date' => time(),
- 'site_name' => $config->get('name'),
- 'count' => count($nodes),
- 'nodes' => $nodes_data,
- 'entrees' => $entrees,
- 'language' => $current_langcode,
- );
- // https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/
- // cache is invalidated in edlp_corpus.module by tags
- $data['#cache'] = [
- 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
- 'tags' => ['rebuild-corpus-cache'],
- 'contexts' => ['languages:language_content'],
- ];
- // $response = new JsonResponse();
- // $response->setData($data);
- $response = new CacheableJsonResponse($data);
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
- return $response;
- return array(
- '#markup'=>'Hello Corpus'
- );
- }
- // _ _ _
- // | | __ _ __| |_ __| |___ __ ___
- // | |__/ _` (_-< _/ _` / _ \/ _(_-<
- // |____\__,_/__/\__\__,_\___/\__/__/
- private function query() {
- $query = \Drupal::entityQuery('node')
- ->condition('status', 1)
- ->condition('type', 'enregistrement')
- ->sort('created', 'DESC')
- ->range(0,20);
- $nids = $query->execute();
- $this->lastdocs_nodes = entity_load_multiple('node', $nids);
- // record an array of nids for corpus map filtering
- $this->lastdocs_nids = [];
- foreach($nids as $key => $nid){
- $this->lastdocs_nids[] = $nid;
- }
- }
- private function toRenderable(){
- $this->query();
- // dpm($this->next_event_node);
- return array(
- "#theme"=>'edlp_corpus_lastdocs',
- '#lastdocs_nodes' => $this->lastdocs_nodes
- );
- }
- /**
- * Display lastdocs as a page.
- *
- * @return renderable array
- */
- public function lastdocs() {
- return $this->toRenderable();
- }
- /**
- * Get lastdocs data as json through ajax.
- *
- * @return json
- */
- public function lastdocsjson() {
- $renderable = $this->toRenderable();
- // $rendered = render($renderable);
- // We can't render directly the entity as it throw an exception with cachable data
- //http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
- $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
- return render($renderable);
- });
- $data = [
- 'rendered'=> $rendered,
- 'title'=>'Last Documents',
- 'documents_lies' => $this->lastdocs_nids,
- ];
- // translations links
- // use Drupal\Core\Url;
- // use Drupal\Core\Language\LanguageInterface;
- $route_name = 'edlp_corpus.lastdocs';
- $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
- if (isset($links->links)) {
- $translations_build = [
- '#theme' => 'links__language_block',
- '#links' => $links->links,
- '#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
- '#set_active_class' => TRUE,
- ];
- $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
- $data['translations_links'] = $translations_rendered;
- }
- $data['#cache'] = [
- 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
- 'tags' => ['edlp-lastdocs-cache']
- ];
- // $response = new JsonResponse();
- // $response->setData($data);
- $response = new CacheableJsonResponse($data);
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
- return $response;
- }
- // _ _ _ _ ___ _
- // /_\ _ _| |_(_)__| |___ ___ |_ _|_ _ __| |_____ __
- // / _ \| '_| _| / _| / -_|_-< | || ' \/ _` / -_) \ /
- // /_/ \_\_| \__|_\__|_\___/__/ |___|_||_\__,_\___/_\_\
- private function articlesQuery() {
- $query = \Drupal::entityQuery('node')
- ->condition('status', 1)
- ->condition('type', 'enregistrement')
- ->condition('body', '', "<>")
- ->sort('created', 'DESC');
- // ->range(0,20);
- $nids = $query->execute();
- $nodes = entity_load_multiple('node', $nids);
- $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $this->articles_nodes = [];
- $this->articles_nids = [];
- foreach ($nodes as $node) {
- // remove masqué
- $sid = WorkflowManager::getCurrentStateId($node, 'field_workflow');
- if($sid != 'corpus_documents_publie') continue;
- // TODO: check if article is translated
- if ($node->getTranslation($current_langcode)->body->isEmpty()) continue;
- $this->articles_nodes[] = $node;
- // record an array of nids for corpus map filtering
- $this->articles_nids[] = $node->get('nid')->getString();
- }
- }
- private function articlesToRenderable(){
- $this->articlesQuery();
- // dpm($this->next_event_node);
- return array(
- "#theme"=>'edlp_corpus_articlesindex',
- '#articles_nodes' => $this->articles_nodes
- );
- }
- /**
- * Display lastdocs as a page.
- *
- * @return renderable array
- */
- public function articlesindex() {
- return $this->articlesToRenderable();
- }
- /**
- * Get lastdocs data as json through ajax.
- *
- * @return json
- */
- public function articlesindexjson() {
- $renderable = $this->articlesToRenderable();
- // $rendered = render($renderable);
- // We can't render directly the entity as it throw an exception with cachable data
- //http://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/#the-dreaded-leaked-metadata-error
- $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($renderable) {
- return render($renderable);
- });
- $data = [
- 'rendered'=> $rendered,
- 'title'=>'Articles',
- 'articles' => $this->articles_nids,
- 'documents_lies' => $this->articles_nids,
- ];
- // translations links
- // use Drupal\Core\Url;
- // use Drupal\Core\Language\LanguageInterface;
- $route_name = 'edlp_corpus.articlesindex';
- $links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
- if (isset($links->links)) {
- $translations_build = [
- '#theme' => 'links__language_block',
- '#links' => $links->links,
- '#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
- '#set_active_class' => TRUE,
- ];
- $translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
- $data['translations_links'] = $translations_rendered;
- }
- $data['#cache'] = [
- 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
- 'tags' => ['edlp-articlesindex-cache']
- ];
- // $response = new JsonResponse();
- // $response->setData($data);
- $response = new CacheableJsonResponse($data);
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
- $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
- return $response;
- }
- }
|