EnforcedResponse.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Symfony\Component\HttpFoundation\Response;
  4. /**
  5. * A wrapper containing a response which is to be enforced upon delivery.
  6. *
  7. * The FormBuilder throws an EnforcedResponseException whenever a form
  8. * desires to explicitly set a response object. Exception handlers capable of
  9. * setting the response should extract the response object of such an exception
  10. * using EnforcedResponse::createFromException(). Then wrap it into an
  11. * EnforcedResponse object and replace the original response with the wrapped
  12. * response.
  13. *
  14. * @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber::onKernelException()
  15. * @see Drupal\Core\EventSubscriber\DefaultExceptionSubscriber::createHtmlResponse()
  16. * @see Drupal\Core\EventSubscriber\DefaultExceptionHtmlSubscriber::createResponse()
  17. */
  18. class EnforcedResponse extends Response {
  19. /**
  20. * The wrapped response object.
  21. *
  22. * @var \Symfony\Component\HttpFoundation\Response
  23. */
  24. protected $response;
  25. /**
  26. * Constructs a new enforced response from the given exception.
  27. *
  28. * Note that it is necessary to traverse the exception chain when searching
  29. * for an enforced response. Otherwise it would be impossible to find an
  30. * exception thrown from within a twig template.
  31. *
  32. * @param \Exception $e
  33. * The exception where the enforced response is to be extracted from.
  34. *
  35. * @return \Drupal\Core\Form\EnforcedResponse|null
  36. * The enforced response or NULL if the exception chain does not contain a
  37. * \Drupal\Core\Form\EnforcedResponseException exception.
  38. */
  39. public static function createFromException(\Exception $e) {
  40. while ($e) {
  41. if ($e instanceof EnforcedResponseException) {
  42. return new static($e->getResponse());
  43. }
  44. $e = $e->getPrevious();
  45. }
  46. }
  47. /**
  48. * Constructs an enforced response.
  49. *
  50. * Use EnforcedResponse::createFromException() instead.
  51. *
  52. * @param \Symfony\Component\HttpFoundation\Response $response
  53. * The response to wrap.
  54. */
  55. public function __construct(Response $response) {
  56. parent::__construct('', 500);
  57. $this->response = $response;
  58. }
  59. /**
  60. * Returns the wrapped response.
  61. *
  62. * @return \Symfony\Component\HttpFoundation\Response
  63. * The wrapped response.
  64. */
  65. public function getResponse() {
  66. return $this->response;
  67. }
  68. }