cakephp-htmx/src/Controller/Component/HtmxComponent.php

141 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace CakeHtmx\Controller\Component;
use Cake\Controller\Component;
use Cake\Log\Log;
use Cake\Routing\Router;
/**
* Htmx component
*/
class HtmxComponent extends Component
{
/**
* Default configuration.
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [];
/**
* @var \Cake\Controller\Controller
*/
protected $controller;
/**
* @param array $config
* @return void
*/
public function initialize(array $config): void {
parent::initialize($config);
$this->controller = $this->getController();
}
/**
* Convenience method to check if request is from HTMX
*
* @return bool
*/
public function isHtmx()
{
return $this->controller->getRequest()->getHeaderLine('HX-Request') === 'true';
}
/**
* Convenience method to check if request is Boosted
*
* @return bool
*/
public function isBoosted()
{
return $this->controller->getRequest()->getHeaderLine('HX-Boosted') === 'true';
}
/**
* Get HTMX target id
*
* @return string|null
*/
public function getHtmxTarget()
{
$target = $this->controller->getRequest()->getHeaderLine('HX-Target');
return $target ?: null;
}
/**
* Get HTMX trigger id
*
* @return string|null
*/
public function getHtmxTrigger()
{
$trigger = $this->controller->getRequest()->getHeaderLine('HX-Trigger');
return $trigger ?: null;
}
/**
* Get HTMX trigger name
*
* @return string|null
*/
public function getHtmxTriggerName()
{
$trigger = $this->controller->getRequest()->getHeaderLine('HX-Trigger-Name');
return $trigger ?: null;
}
/**
* Set headers to cache this request.
* Opposite of Controller::disableCache()
*
* @param array|string $redirectTo
* @param bool $full if client side redirect should be a full page reload or not
*
* @return void
*/
public function clientSideRedirect(array|string $redirectTo, bool $full = false): void
{
$response = $this->controller->getResponse();
if (is_array($redirectTo)) {
$redirectTo = Router::url($redirectTo);
}
$header = $full ? 'HX-Redirect' : 'HX-Location';
$response = $response->withHeader($header, $redirectTo);
$this->controller->setResponse($response);
}
/**
* Set headers to cache this request.
* Opposite of Controller::disableCache()
*
* @param array|string $redirectTo
* @param bool $full if client side redirect should be a full page reload or not
*
* @return void
*/
public function clientSideRefresh(): void
{
$response = $this->controller->getResponse();
$response = $response->withHeader('HX-Refresh', 'true');
$this->controller->setResponse($response);
}
/**
* @return void
*/
public function indexHtmx()
{
if ($this->isHtmx() && $this->getHtmxTarget() == 'table-container') {
return $this->render('/element/' . $this->request->getParam('controller') . '/index/table', 'ajax');
}
}
}