PathTranslator.php in Decoupled Router 2.x
File
src/Controller/PathTranslator.php
View source
<?php
namespace Drupal\decoupled_router\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Language\LanguageInterface;
use Drupal\decoupled_router\PathTranslatorEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class PathTranslator extends ControllerBase {
protected $eventDispatcher;
protected $httpKernel;
public function __construct(EventDispatcherInterface $event_dispatcher, HttpKernelInterface $http_kernel) {
$this->eventDispatcher = $event_dispatcher;
$this->httpKernel = $http_kernel;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('event_dispatcher'), $container
->get('http_kernel'));
}
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.');
}
$event = new PathTranslatorEvent($this->httpKernel, $request, HttpKernelInterface::MASTER_REQUEST, sprintf('/%s', ltrim($path, '/')));
$this->eventDispatcher
->dispatch(PathTranslatorEvent::TRANSLATE, $event);
$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;
}
}