Skip to content

Commit

Permalink
handle new X-Inject-Alertify header in AlertifyListener
Browse files Browse the repository at this point in the history
  • Loading branch information
adpdsr committed Nov 29, 2017
1 parent 6583174 commit 0fb2a86
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
21 changes: 15 additions & 6 deletions EventListener/AlertifyListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,31 @@ public function onKernelResponse(FilterResponseEvent $event)

/**
* Injects the alertify view into the given Response just before </body> 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, '</body>');
$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);
}
}
Expand Down
21 changes: 21 additions & 0 deletions Exception/IncompatibleStatusCodeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Troopers\AlertifyBundle\Exception;

/**
* Class IncompatibleStatusCodeException.
*/
class IncompatibleStatusCodeException extends \Exception
{
/**
* IncompatibleStatusCodeException constructor.
*
* @param string $message
* @param int $code
* @param null $previous
*/
public function __construct($message = "Status code 204 can't have content, please choose another one.", $code = 544, $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

0 comments on commit 0fb2a86

Please sign in to comment.