3 declare(strict_types = 1);
7 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\Serialization\Yaml;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11 use Symfony\Component\HttpFoundation\JsonResponse;
12 use Symfony\Component\HttpFoundation\RequestStack;
17 class Docs implements ContainerInjectionInterface {
31 private $moduleHandler;
38 private $requestStack;
52 public static function create(ContainerInterface $container) {
54 $container->get(
'module_handler'),
55 $container->get(
'request_stack')
63 ModuleHandlerInterface $moduleHandler,
64 RequestStack $requestStack
66 $this->moduleHandler = $moduleHandler;
67 $this->requestStack = $requestStack;
68 $this->serializer =
new Yaml();
76 return new JsonResponse([
"version" => 1,
"url" =>
"/api/1"]);
86 $modulePath = $this->moduleHandler->getModule(
'dkan_api')->getPath();
87 $ymlSpecPath = $modulePath .
'/docs/dkan_api_openapi_spec.yml';
88 $ymlSpec = file_get_contents($ymlSpecPath);
90 return $this->serializer->decode($ymlSpec);
100 if ($this->requestStack->getCurrentRequest()->get(
'authentication') ===
"false") {
101 $spec = $this->getPublic();
107 $jsonSpec = json_encode($spec);
108 return $this->sendResponse($jsonSpec);
120 private function getPublic() {
121 $publicSpec = $this->removeAuthenticatedEndpoints($this->spec);
122 $cleanSpec = $this->cleanUpEndpoints($publicSpec);
123 unset($cleanSpec[
'components'][
'securitySchemes']);
136 private function removeAuthenticatedEndpoints(array $spec) {
137 foreach ($spec[
'paths'] as $path => $operations) {
138 $this->removeAuthenticatedOperations($operations, $path, $spec);
153 private function removeAuthenticatedOperations(array $operations,
string $path, array &$spec) {
154 foreach ($operations as $operation => $details) {
155 if (isset($spec[
'paths'][$path][$operation][
'security'])) {
156 unset($spec[
'paths'][$path][$operation]);
170 private function cleanUpEndpoints(array $spec) {
171 foreach ($spec[
'paths'] as $path => $operations) {
172 if (empty($operations)) {
173 unset($spec[
'paths'][$path]);
188 private function sendResponse(
string $jsonSpec) {
189 return new JsonResponse(
193 'Content-type' =>
'application/json',
194 'Access-Control-Allow-Origin' =>
'*',