Skip to content

Instantly share code, notes, and snippets.

@enumag
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enumag/cea679af2e6349037507 to your computer and use it in GitHub Desktop.
Save enumag/cea679af2e6349037507 to your computer and use it in GitHub Desktop.
HistoryListener
<?php
namespace VojtechDobes\NetteAjax;
use Nette\Application\Application;
use Nette\Object
class HistoryListener extends Object
{
/** @var Http\IRequest */
private $httpRequest;
/** @var IRouter */
private $router;
/** @var bool */
private $forwardHasHappened = FALSE;
/** @var bool */
private $errorHasHappened = FALSE;
/**
* @param Http\IRequest
* @param IRouter
*/
public function __construct(Http\IRequest $httpRequest, IRouter $router)
{
$this->httpRequest = $httpRequest;
$this->router = $router;
}
public function register(Application $application)
{
$application->onRequest[] = array($this, 'onRequest');
$application->onResponse[] = array($this, 'onResponse');
$application->onError[] = array($this, 'onError');
}
public function onRequest($application, $request)
{
if (count($application->getRequests()) > 1) {
$this->forwardHasHappened = TRUE;
}
}
public function onError($application, $exception)
{
$this->errorHasHappened = TRUE;
}
public function onResponse($application, $response)
{
if (!$this->errorHasHappened && $response instanceof JsonResponse && ($payload = $response->getPayload()) instanceof \stdClass) {
if (!$this->forwardHasHappened && isset($payload->redirect)) {
$url = new Http\UrlScript($payload->redirect);
$url->setScriptPath($this->httpRequest->url->scriptPath);
$httpRequest = new Http\Request($url);
if ($this->router->match($httpRequest) !== NULL) {
$prop = new Property('Nette\Application\Application', 'httpRequest');
$prop->setAccessible(TRUE);
$prop->setValue($application, $httpRequest);
$application->run();
exit;
}
} elseif ($this->forwardHasHappened && !isset($payload->redirect)) {
$payload->redirect = $application->getPresenter()->link('this');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment