|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Created by PhpStorm. |
| 4 | + * User: bertrand |
| 5 | + * Date: 03/12/18 |
| 6 | + * Time: 10:10 |
| 7 | + */ |
| 8 | + |
| 9 | +namespace Drupal\itc_jsonapi\Controller; |
| 10 | + |
| 11 | + |
| 12 | +use Drupal\Core\Cache\CacheableMetadata; |
| 13 | +use Drupal\Core\Language\LanguageInterface; |
| 14 | +use Drupal\itc_jsonapi\CacheableJsonApiResponse; |
| 15 | +use Drupal\itc_jsonapi\JsonApiResponse; |
| 16 | +use Symfony\Component\HttpFoundation\Request; |
| 17 | + |
| 18 | +class MetatagController { |
| 19 | + |
| 20 | + const ALLOWED_ENTITY_TYPES = ['node', 'taxonomy_term']; |
| 21 | + |
| 22 | + /** |
| 23 | + * @var \Drupal\Core\Entity\EntityRepositoryInterface |
| 24 | + */ |
| 25 | + protected $entityRepository; |
| 26 | + |
| 27 | + /** |
| 28 | + * @var \Drupal\metatag\MetatagManagerInterface |
| 29 | + */ |
| 30 | + protected $metatagManager; |
| 31 | + |
| 32 | + public function __construct() { |
| 33 | + $this->entityRepository = \Drupal::service('entity.repository'); |
| 34 | + $this->languageManager = \Drupal::languageManager(); |
| 35 | + $this->metatagManager = \Drupal::service('metatag.manager'); |
| 36 | + } |
| 37 | + |
| 38 | + public function metatag(Request $request) { |
| 39 | + $entity_type = $request->query->get('entity_type'); |
| 40 | + $uuid = $request->query->get('id'); |
| 41 | + if (!in_array($entity_type, self::ALLOWED_ENTITY_TYPES)) { |
| 42 | + return new JsonApiResponse(); |
| 43 | + } |
| 44 | + if (!is_string($uuid)) { |
| 45 | + return new JsonApiResponse(); |
| 46 | + } |
| 47 | + /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ |
| 48 | + $entity = $this->entityRepository->loadEntityByUuid($entity_type, $uuid); |
| 49 | + if (empty($entity)) { |
| 50 | + return new JsonApiResponse(); |
| 51 | + } |
| 52 | + $language = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); |
| 53 | + $langcode = $language->getId(); |
| 54 | + if ($entity->hasTranslation($langcode)) { |
| 55 | + $entity = $entity->getTranslation($langcode); |
| 56 | + } |
| 57 | + $tags = $this->metatagManager->tagsFromEntityWithDefaults($entity); |
| 58 | + $metatags = $this->metatagManager->generateElements($tags, $entity)['#attached']['html_head']; |
| 59 | + $data = [ |
| 60 | + 'data' => [], |
| 61 | + ]; |
| 62 | + foreach ($metatags as $tag) { |
| 63 | + $data['data'][] = $tag[0]; |
| 64 | + } |
| 65 | + $response = new JsonApiResponse(json_encode($data)); |
| 66 | + return $response; |
| 67 | + } |
| 68 | +} |
0 commit comments