<?php
/**
* Copyright (C) 2021 Rhyme Digital, LLC.
*
* @link https://rhyme.digital
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*/
namespace Rhyme\WMassArtsHub\Module\Profile;
use Contao\Input;
use Contao\System;
use Contao\ModuleModel;
use Contao\CoreBundle\Exception\AjaxRedirectResponseException;
use Contao\CoreBundle\Exception\RedirectResponseException;
use Haste\Http\Response\JsonResponse;
use Haste\Ajax\ReloadHelper;
/**
* Class AjaxFilter
* @package Rhyme\WMassArtsHub\Module
*/
abstract class AjaxFilter extends Filter
{
/**
* Display a wildcard in the back end
* @return string
* @throws \Exception
*/
public function generate()
{
$strBuffer = parent::generate();
if (TL_MODE === 'BE')
{
return $strBuffer;
}
// Add the data attributes
if ($this->Template->cssID)
{
$strBuffer = str_replace($this->Template->cssID, $this->Template->cssID.' data-module="'.$this->id.'"', $strBuffer);
$strBuffer = str_replace($this->Template->cssID, $this->Template->cssID.' data-id="'.$this->id.'"', $strBuffer);
$strBuffer = str_replace($this->Template->cssID, $this->Template->cssID.' data-pageid="{{page::id}}"', $strBuffer);
$strBuffer = str_replace($this->Template->cssID, $this->Template->cssID.' data-table="'.ModuleModel::getTable().'"', $strBuffer);
}
return $strBuffer;
}
/**
*
*/
protected function compile()
{
// Haste AJAX reload
ReloadHelper::subscribe(
ReloadHelper::getUniqid(ReloadHelper::TYPE_MODULE, $this->id),
['reloadFilter-'.$this->id]
);
parent::compile();
// Make sure this module has an ID
$arrCssID = (array)$this->cssID;
$arrCssID[0] = $arrCssID[0] ?: 'profilefilter'.$this->id;
$this->cssID = $arrCssID;
// Add AJAX scripts
$GLOBALS['TL_JAVASCRIPT']['profileFilterAjax'] = 'web/bundles/rhymewmassartshub/assets/js/frontend/profileFilter/ajax.js|static';
$GLOBALS['TL_BODY']['historyjs'] = '<script src="https://cdnjs.cloudflare.com/ajax/libs/history.js/1.8/native.history.min.js" integrity="sha512-LW9lY12yhdxezhOnfueR/bF7GdraV3ZCZpdTTUqrq6ifCsp4wmnlBbw8/qTjs+9jqLXZn+cBVYN9rlQz52UVkA==" crossorigin="anonymous"></script>';
$GLOBALS['TL_BODY']['profileFilterAjax'.$this->id] = "
<script>
jQuery(document).ready(function(){
ArtsHub.ProfileFilterAjax.create(jQuery('#".$arrCssID[0]."'), {
});
});
</script>";
}
/**
* Handle incoming filter requests and generate appropriate URL
* @return void
*/
protected function handleRequests()
{
try
{
parent::handleRequests();
}
catch (AjaxRedirectResponseException $e)
{
// There was a POST, so we need to send a json response back
$response = $e->getResponse();
$newUrl = $response->getContent();
$container = System::getContainer();
// Append the page as a GET param
if (Input::post('page'))
{
$newUrl .= (\strpos($newUrl, '?') !== false ? '&' : '?') . 'page='.Input::post('page');
}
$objResponse = new JsonResponse([
'newUrl' => $newUrl,
'REQUEST_TOKEN' => $container->get('contao.csrf.token_manager')->getToken($container->getParameter('contao.csrf_token_name'))->getValue(),
]);
$objResponse->send();
exit;
}
}
}