diff --git a/EventListener/AlertifyListener.php b/EventListener/AlertifyListener.php index 4133444..b24ecdd 100644 --- a/EventListener/AlertifyListener.php +++ b/EventListener/AlertifyListener.php @@ -57,22 +57,31 @@ public function onKernelResponse(FilterResponseEvent $event) /** * Injects the alertify view into the given Response just before tag. + * + * @param Response $response + * @param Request $request + * + * @throws IncompatibleStatusCodeException */ protected function injectAlertify(Response $response, Request $request) { - if ($response instanceof RedirectResponse) { - return; - } - $content = $response->getContent(); $endBodyPos = strripos($content, ''); $hasBody = false !== $endBodyPos; $hasMetaRefresh = false !== strripos($content, 'http-equiv="refresh"'); + $forceInject = $response->headers->get('X-Inject-Alertify', false); $isRedirectResponse = $response instanceof RedirectResponse; - if ($hasBody && !$hasMetaRefresh && !$isRedirectResponse) { + if ($hasBody && !$hasMetaRefresh && !$isRedirectResponse || $forceInject) { + if ($response->getStatusCode() === 204) { + throw new IncompatibleStatusCodeException(); + } $alertify = $this->alertifySessionHandler->handle($this->session, $this->twig); - $content = substr($content, 0, $endBodyPos).$alertify.substr($content, $endBodyPos); + if ($endBodyPos) { + $content = substr($content, 0, $endBodyPos).$alertify.substr($content, $endBodyPos); + } else { + $content .= $alertify; + } $response->setContent($content); } } diff --git a/Exception/IncompatibleStatusCodeException.php b/Exception/IncompatibleStatusCodeException.php new file mode 100644 index 0000000..22cd3ec --- /dev/null +++ b/Exception/IncompatibleStatusCodeException.php @@ -0,0 +1,21 @@ +Burn some cats ``` + +## Custom header + +If you want to force the trigger of an alert, after an ajax call for example, you need to send through the response a custom header : `X-Inject-Alertify`. When its value is set to `true`, then the alert append at the end of the response content, even if it is empty. Note that the `204` status code (No content) is incompatible with this header, as the 204 response MUST NOT include a message-body. + +## Example : + +```php +return new Response(null, 200, [ + 'X-Inject-Alertify' => true +]); +``` \ No newline at end of file