|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Drupal\jsonapi_frontend_layout\Controller; |
| 6 | + |
| 7 | +use Drupal\Core\Cache\CacheableJsonResponse; |
| 8 | +use Drupal\Core\Cache\CacheableMetadata; |
| 9 | +use Drupal\Core\Controller\ControllerBase; |
| 10 | +use Drupal\Core\Entity\ContentEntityInterface; |
| 11 | +use Drupal\jsonapi_frontend\Service\PathResolverInterface; |
| 12 | +use Drupal\jsonapi_frontend_layout\Service\LayoutTreeBuilder; |
| 13 | +use Symfony\Component\DependencyInjection\ContainerInterface; |
| 14 | +use Symfony\Component\HttpFoundation\Request; |
| 15 | + |
| 16 | +/** |
| 17 | + * Layout-aware resolver endpoint. |
| 18 | + */ |
| 19 | +final class LayoutResolverController extends ControllerBase { |
| 20 | + |
| 21 | + private const CONTENT_TYPE = 'application/vnd.api+json; charset=utf-8'; |
| 22 | + |
| 23 | + public function __construct( |
| 24 | + private readonly PathResolverInterface $resolver, |
| 25 | + private readonly LayoutTreeBuilder $layoutTreeBuilder, |
| 26 | + ) {} |
| 27 | + |
| 28 | + public static function create(ContainerInterface $container): self { |
| 29 | + return new self( |
| 30 | + $container->get('jsonapi_frontend.path_resolver'), |
| 31 | + $container->get('jsonapi_frontend_layout.layout_tree_builder'), |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + public function resolve(Request $request): CacheableJsonResponse { |
| 36 | + $path = (string) $request->query->get('path', ''); |
| 37 | + |
| 38 | + if (trim($path) === '') { |
| 39 | + return $this->errorResponse( |
| 40 | + status: 400, |
| 41 | + title: 'Bad Request', |
| 42 | + detail: 'Missing required query parameter: path', |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + $langcode = $request->query->get('langcode'); |
| 47 | + $langcode = is_string($langcode) && $langcode !== '' ? $langcode : NULL; |
| 48 | + |
| 49 | + $result = $this->resolver->resolve($path, $langcode); |
| 50 | + |
| 51 | + $cacheable = new CacheableMetadata(); |
| 52 | + $cacheable->setCacheMaxAge($this->getCacheMaxAge()); |
| 53 | + $cacheable->addCacheTags(['config:jsonapi_frontend.settings']); |
| 54 | + $cacheable->addCacheContexts([ |
| 55 | + 'url.query_args:path', |
| 56 | + 'url.query_args:langcode', |
| 57 | + 'url.site', |
| 58 | + ]); |
| 59 | + |
| 60 | + // Mirror jsonapi_frontend's language fallback cache behavior. |
| 61 | + $config = $this->config('jsonapi_frontend.settings'); |
| 62 | + $langcode_fallback = (string) ($config->get('resolver.langcode_fallback') ?? 'site_default'); |
| 63 | + if ($langcode_fallback === 'current') { |
| 64 | + $cacheable->addCacheContexts(['languages:language_content']); |
| 65 | + } |
| 66 | + |
| 67 | + // If this resolved to an entity, attempt to attach a layout tree. |
| 68 | + if (($result['resolved'] ?? FALSE) === TRUE && ($result['kind'] ?? NULL) === 'entity' && is_array($result['entity'] ?? NULL)) { |
| 69 | + $entity = $this->loadResolvedEntity($result['entity'], $langcode); |
| 70 | + if ($entity) { |
| 71 | + $cacheable->addCacheableDependency($entity); |
| 72 | + $layout = $this->layoutTreeBuilder->build($entity, $cacheable); |
| 73 | + if ($layout) { |
| 74 | + $result['layout'] = $layout; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + $response = new CacheableJsonResponse($result, 200, [ |
| 80 | + 'Content-Type' => self::CONTENT_TYPE, |
| 81 | + ]); |
| 82 | + |
| 83 | + $response->addCacheableDependency($cacheable); |
| 84 | + $this->applySecurityHeaders($response, $cacheable->getCacheMaxAge()); |
| 85 | + |
| 86 | + return $response; |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Load the resolved entity (by UUID) from a resolver result. |
| 91 | + * |
| 92 | + * @param array{type?: mixed, id?: mixed, langcode?: mixed} $entity_info |
| 93 | + * The "entity" object from jsonapi_frontend. |
| 94 | + */ |
| 95 | + private function loadResolvedEntity(array $entity_info, ?string $langcode): ?ContentEntityInterface { |
| 96 | + $resource_type = $entity_info['type'] ?? NULL; |
| 97 | + $uuid = $entity_info['id'] ?? NULL; |
| 98 | + |
| 99 | + if (!is_string($resource_type) || !is_string($uuid) || $resource_type === '' || $uuid === '') { |
| 100 | + return NULL; |
| 101 | + } |
| 102 | + |
| 103 | + $parts = explode('--', $resource_type, 2); |
| 104 | + if (count($parts) !== 2) { |
| 105 | + return NULL; |
| 106 | + } |
| 107 | + |
| 108 | + [$entity_type_id] = $parts; |
| 109 | + if ($entity_type_id === '') { |
| 110 | + return NULL; |
| 111 | + } |
| 112 | + |
| 113 | + $definition = $this->entityTypeManager()->getDefinition($entity_type_id, FALSE); |
| 114 | + if (!$definition || !$definition->entityClassImplements(ContentEntityInterface::class)) { |
| 115 | + return NULL; |
| 116 | + } |
| 117 | + |
| 118 | + $storage = $this->entityTypeManager()->getStorage($entity_type_id); |
| 119 | + $entities = $storage->loadByProperties(['uuid' => $uuid]); |
| 120 | + $entity = $entities ? reset($entities) : NULL; |
| 121 | + |
| 122 | + if (!$entity instanceof ContentEntityInterface) { |
| 123 | + return NULL; |
| 124 | + } |
| 125 | + |
| 126 | + // Apply the negotiated langcode from the resolver response if possible. |
| 127 | + $resolved_langcode = $entity_info['langcode'] ?? NULL; |
| 128 | + $resolved_langcode = is_string($resolved_langcode) && $resolved_langcode !== '' ? $resolved_langcode : $langcode; |
| 129 | + if ($resolved_langcode && method_exists($entity, 'hasTranslation') && $entity->hasTranslation($resolved_langcode)) { |
| 130 | + $entity = $entity->getTranslation($resolved_langcode); |
| 131 | + } |
| 132 | + |
| 133 | + // Re-check view access (defense in depth). |
| 134 | + return $entity->access('view') ? $entity : NULL; |
| 135 | + } |
| 136 | + |
| 137 | + private function errorResponse(int $status, string $title, string $detail): CacheableJsonResponse { |
| 138 | + $response = new CacheableJsonResponse([ |
| 139 | + 'errors' => [ |
| 140 | + [ |
| 141 | + 'status' => (string) $status, |
| 142 | + 'title' => $title, |
| 143 | + 'detail' => $detail, |
| 144 | + ], |
| 145 | + ], |
| 146 | + ], $status, [ |
| 147 | + 'Content-Type' => self::CONTENT_TYPE, |
| 148 | + ]); |
| 149 | + |
| 150 | + $cacheable = new CacheableMetadata(); |
| 151 | + $cacheable->setCacheMaxAge(0); |
| 152 | + $response->addCacheableDependency($cacheable); |
| 153 | + $this->applySecurityHeaders($response, 0); |
| 154 | + |
| 155 | + return $response; |
| 156 | + } |
| 157 | + |
| 158 | + private function getCacheMaxAge(): int { |
| 159 | + if (!$this->currentUser()->isAnonymous()) { |
| 160 | + return 0; |
| 161 | + } |
| 162 | + |
| 163 | + $config = $this->config('jsonapi_frontend.settings'); |
| 164 | + $max_age = (int) ($config->get('resolver.cache_max_age') ?? 0); |
| 165 | + |
| 166 | + return max(0, $max_age); |
| 167 | + } |
| 168 | + |
| 169 | + private function applySecurityHeaders(CacheableJsonResponse $response, int $max_age): void { |
| 170 | + $response->headers->set('X-Content-Type-Options', 'nosniff'); |
| 171 | + |
| 172 | + if ($max_age > 0) { |
| 173 | + $response->headers->set('Cache-Control', 'public, max-age=' . $max_age); |
| 174 | + } |
| 175 | + else { |
| 176 | + $response->headers->set('Cache-Control', 'no-store'); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | +} |
0 commit comments