<?php

declare(strict_types=1);

namespace Drupal\sobki_admin\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Redirect to layout builder form on node creation.
 */
class NodeInsertRedirection implements EventSubscriberInterface {

  public const int REDIRECT_WEIGHT = -10;

  public const string REDIRECT_ATTRIBUTE = 'node_insert_redirection_url';

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = [];
    $events[KernelEvents::RESPONSE] = ['checkRedirectIssued', static::REDIRECT_WEIGHT];
    return $events;
  }

  /**
   * Checks if a redirect url was set and sets the event response if possible.
   *
   * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
   *   The response event.
   */
  public function checkRedirectIssued(ResponseEvent $event): void {
    $request = $event->getRequest();
    $redirect_url = $request->attributes->get(static::REDIRECT_ATTRIBUTE);
    if (isset($redirect_url) && \is_string($redirect_url)) {
      $event->setResponse(new RedirectResponse($redirect_url));
    }
  }

}
