EntryPoint.php in JSON:API 8
File
src/Controller/EntryPoint.php
View source
<?php
namespace Drupal\jsonapi\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntryPoint extends ControllerBase {
protected $resourceTypeRepository;
protected $renderer;
public function __construct(ResourceTypeRepositoryInterface $resource_type_repository, RendererInterface $renderer) {
$this->resourceTypeRepository = $resource_type_repository;
$this->renderer = $renderer;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('jsonapi.resource_type.repository'), $container
->get('renderer'));
}
public function index() {
$context = new RenderContext();
$do_build_urls = function () {
$self = Url::fromRoute('jsonapi.resource_list')
->setAbsolute();
$resources = array_filter($this->resourceTypeRepository
->all(), function ($resource) {
return !$resource
->isInternal();
});
return array_reduce($resources, function (array $carry, ResourceType $resource_type) {
$url = Url::fromRoute(sprintf('jsonapi.%s.collection', $resource_type
->getTypeName()))
->setAbsolute();
$carry[$resource_type
->getTypeName()] = $url
->toString();
return $carry;
}, [
'self' => $self
->toString(),
]);
};
$urls = $this->renderer
->executeInRenderContext($context, $do_build_urls);
$json_response = new CacheableJsonResponse([
'data' => [],
'links' => $urls,
]);
if (!$context
->isEmpty()) {
$json_response
->addCacheableDependency($context
->pop());
}
return $json_response;
}
}