Redirect.php
<?php
namespace Lia;
class Redirect extends \Lia\Compo {
//@TODO write tests for Redirect component
protected $redirectUrl;
protected $withContent = false;
protected $withMessage = false;
protected $statusCode = 302;
protected $message = null;
public function apiGoto_lia_goto_goto($url, $statusCode=302){
$this->redirectUrl = $url;
$this->statusCode = $statusCode;
$this->withContent = false;
$this->withMessage = false;
}
public function apiSetMessage_lia_goto_gotoSetMessage($message){
$this->message = $message;
$this->withMessage = true;
$this->withContent = false;
}
public function apiWithMessageMessage_lia_goto_gotoWithMessage($url, $message, $statusCode=302){
$this->redirectUrl = $url;
$this->withContent = false;
$this->withMessage = true;
$this->message = $message;
$this->statusCode = $statusCode;
}
/**
* Show the content of this request at the given url
*/
public function apiWithContent_lia_goto_gotoWithContent($url, $statusCode=302){
$this->redirectUrl = $url;
$this->withContent = true;
$this->statusCode = $statusCode;
$this->withMessage = false;
}
public function apiGetMessage_lia_goto_getGotoMessage(){
$id = $_GET['message_id']??null;
if ($id===null)return false;
$cacheFile = $this->lia->getCacheFile('lia.Redirect.withMessage.'.$id);
if (!is_file($cacheFile))return false;
$content = file_get_contents($cacheFile);
// unlink($cacheFile);
return $content;
}
public function onEmit_Server_willDisplayContent($response){
if ($this->redirectUrl=='')return;
$id = uniqid().'-'.uniqid();
//@DEBUG return to the 5 minute cache (instead of 5 seconds!)
// $this->lia->cacheFile('lia.Redirect.withMessage.'.$id, $content, 60*5);
$message =
$this->withMessage
? $this->message
: ($this->withContent ? $response->content : false)
;
$url = $this->redirectUrl;
if ($message!==false){
$this->lia->cacheFile('lia.Redirect.withMessage.'.$id, $message, 5);
$path = parse_url($url, PHP_URL_PATH);
$query = parse_url($url, PHP_URL_QUERY);
$qps = [];
parse_str($query, $qps);
$qps['message_id'] = $id;
$url = $path.'?'.http_build_query($qps);
}
header("Location: {$url}", $this->statusCode ?? 302);
exit;
}
}