JsonapiMaintenanceModeSubscriber.php in Drupal 10
File
core/modules/jsonapi/src/EventSubscriber/JsonapiMaintenanceModeSubscriber.php
View source
<?php
namespace Drupal\jsonapi\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Site\MaintenanceModeEvents;
use Drupal\Core\Site\MaintenanceModeInterface;
use Drupal\jsonapi\JsonApiResource\ErrorCollection;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\ResourceResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
class JsonapiMaintenanceModeSubscriber implements EventSubscriberInterface {
protected $maintenanceMode;
protected $config;
public function __construct(MaintenanceModeInterface $maintenance_mode, ConfigFactoryInterface $config_factory) {
$this->maintenanceMode = $maintenance_mode;
$this->config = $config_factory;
}
public static function getSubscribedEvents() {
$events = [];
$events[MaintenanceModeEvents::MAINTENANCE_MODE_REQUEST][] = [
'onMaintenanceModeRequest',
-800,
];
return $events;
}
public function onMaintenanceModeRequest(RequestEvent $event) {
$request = $event
->getRequest();
if ($request
->getRequestFormat() !== 'api_json') {
return;
}
$header_settings = $this->config
->get('jsonapi.settings')
->get('maintenance_header_retry_seconds');
$retry_after_time = rand($header_settings['min'], $header_settings['max']);
$http_exception = new HttpException(503, $this->maintenanceMode
->getSiteMaintenanceMessage());
$document = new JsonApiDocumentTopLevel(new ErrorCollection([
$http_exception,
]), new NullIncludedData(), new LinkCollection([]));
$response = new ResourceResponse($document, $http_exception
->getStatusCode(), [
'Content-Type' => 'application/vnd.api+json',
'Retry-After' => $retry_after_time,
]);
$event
->setResponse($response);
}
}