You are here

public function PathTranslator::translate in Decoupled Router 8

Same name and namespace in other branches
  1. 2.x src/Controller/PathTranslator.php \Drupal\decoupled_router\Controller\PathTranslator::translate()

Responds with all the information about the path.

1 string reference to 'PathTranslator::translate'
decoupled_router.routing.yml in ./decoupled_router.routing.yml
decoupled_router.routing.yml

File

src/Controller/PathTranslator.php, line 62

Class

PathTranslator
Controller that receives the path to inspect.

Namespace

Drupal\decoupled_router\Controller

Code

public function translate(Request $request) {
  $path = $request->query
    ->get('path');
  if (empty($path)) {
    throw new NotFoundHttpException('Unable to translate empty path. Please send a ?path query string parameter with your request.');
  }

  // Now that we have the path, let's fire an event for translations.
  $event = new PathTranslatorEvent($this->httpKernel, $request, HttpKernelInterface::MASTER_REQUEST, sprintf('/%s', ltrim($path, '/')));

  // Event subscribers are in charge of setting the appropriate response,
  // including cacheability metadata.
  $this->eventDispatcher
    ->dispatch(PathTranslatorEvent::TRANSLATE, $event);

  /** @var \Drupal\Core\Cache\CacheableJsonResponse $response */
  $response = $event
    ->getResponse();
  $response->headers
    ->add([
    'Content-Type' => 'application/json',
  ]);
  $response
    ->getCacheableMetadata()
    ->addCacheContexts([
    'url.query_args:path',
    'languages:' . LanguageInterface::TYPE_CONTENT,
  ]);
  if ($response
    ->getStatusCode() === Response::HTTP_NOT_FOUND) {
    $response
      ->getCacheableMetadata()
      ->addCacheTags([
      '4xx-response',
    ]);
  }
  return $response;
}