2b1466d0a3cc027a60d160a0ed69b6317a9eec4e
[yaffs-website] / web / core / lib / Drupal / Core / Form / EnforcedResponse.php
1 <?php
2
3 namespace Drupal\Core\Form;
4
5 use Symfony\Component\HttpFoundation\Response;
6
7 /**
8  * A wrapper containing a response which is to be enforced upon delivery.
9  *
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
15  * response.
16  *
17  * @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber::onKernelException()
18  * @see Drupal\Core\EventSubscriber\DefaultExceptionSubscriber::createHtmlResponse()
19  * @see Drupal\Core\EventSubscriber\DefaultExceptionHtmlSubscriber::createResponse()
20  */
21 class EnforcedResponse extends Response {
22
23   /**
24    * The wrapped response object.
25    *
26    * @var \Symfony\Component\HttpFoundation\Response;
27    */
28   protected $response;
29
30   /**
31    * Constructs a new enforced response from the given exception.
32    *
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.
36    *
37    * @param \Exception $e
38    *   The exception where the enforced response is to be extracted from.
39    *
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.
43    */
44   public static function createFromException(\Exception $e) {
45     while ($e) {
46       if ($e instanceof EnforcedResponseException) {
47         return new static($e->getResponse());
48       }
49
50       $e = $e->getPrevious();
51     }
52   }
53
54   /**
55    * Constructs an enforced response.
56    *
57    * Use EnforcedResponse::createFromException() instead.
58    *
59    * @param \Symfony\Component\HttpFoundation\Response $response
60    *   The response to wrap.
61    */
62   public function __construct(Response $response) {
63     parent::__construct('', 500);
64     $this->response = $response;
65   }
66
67   /**
68    * Returns the wrapped response.
69    *
70    * @return \Symfony\Component\HttpFoundation\Response
71    *   The wrapped response.
72    */
73   public function getResponse() {
74     return $this->response;
75   }
76
77 }