Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Controller in Drupal via Symfony, returns a JsonResponse cached for 30 seconds.
<?php
declare(strict_types = 1);
namespace Drupal\harlib_open_now\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Component\Serialization\Json;
/**
* Class OpenNowCheckController.
*/
class OpenNowCheckController extends ControllerBase {
const FILE_URI = 'public://libcal/open-now.json';
/**
* Return status of all libraries.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Return the open today in a JsonResponse.
*
* @throws \Exception;
*/
public function getAll() : JsonResponse {
$file = file_get_contents(self::FILE_URI);
if (!$file) {
throw new \Exception('File containing LibCal data does not exist.');
}
$content = Json::decode($file);
$response = new JsonResponse($content);
$response->setMaxAge(30);
$response->setPublic();
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment