3 namespace Drupal\Core\Form;
5 use Symfony\Component\HttpFoundation\Response;
8 * A wrapper containing a response which is to be enforced upon delivery.
10 * The FormBuilder throws an EnforcedResponseException whenever a form
11 * desires to explicitly set a response object. Exception handlers capable of
12 * setting the response should extract the response object of such an exception
13 * using EnforcedResponse::createFromException(). Then wrap it into an
14 * EnforcedResponse object and replace the original response with the wrapped
17 * @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber::onKernelException()
18 * @see Drupal\Core\EventSubscriber\DefaultExceptionSubscriber::createHtmlResponse()
19 * @see Drupal\Core\EventSubscriber\DefaultExceptionHtmlSubscriber::createResponse()
21 class EnforcedResponse extends Response {
24 * The wrapped response object.
26 * @var \Symfony\Component\HttpFoundation\Response;
31 * Constructs a new enforced response from the given exception.
33 * Note that it is necessary to traverse the exception chain when searching
34 * for an enforced response. Otherwise it would be impossible to find an
35 * exception thrown from within a twig template.
37 * @param \Exception $e
38 * The exception where the enforced response is to be extracted from.
40 * @return \Drupal\Core\Form\EnforcedResponse|null
41 * The enforced response or NULL if the exception chain does not contain a
42 * \Drupal\Core\Form\EnforcedResponseException exception.
44 public static function createFromException(\Exception $e) {
46 if ($e instanceof EnforcedResponseException) {
47 return new static($e->getResponse());
50 $e = $e->getPrevious();
55 * Constructs an enforced response.
57 * Use EnforcedResponse::createFromException() instead.
59 * @param \Symfony\Component\HttpFoundation\Response $response
60 * The response to wrap.
62 public function __construct(Response $response) {
63 parent::__construct('', 500);
64 $this->response = $response;
68 * Returns the wrapped response.
70 * @return \Symfony\Component\HttpFoundation\Response
71 * The wrapped response.
73 public function getResponse() {
74 return $this->response;