Files
MageSail/Magesail/Controller/Adminhtml/Tunnel/Logtail.php
T
2026-03-21 03:01:08 -05:00

66 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Controller\Adminhtml\Tunnel;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use MageSail\Magesail\Model\TunnelStatus;
class Logtail extends Action
{
private const BYTES = 8192;
private const LINES = 40;
public function __construct(
Context $context,
private readonly TunnelStatus $tunnelStatus
) {
parent::__construct($context);
}
public function execute()
{
$tunnelId = trim((string) $this->getRequest()->getParam('tunnel_id', ''));
if ($tunnelId === '') {
$json = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$json->setData(['lines' => [], 'error' => 'missing_tunnel_id']);
return $json;
}
$path = $this->tunnelStatus->getLogFilePath($tunnelId);
$lines = [];
if (\is_readable($path)) {
$size = filesize($path);
if ($size !== false && $size > 0) {
$fp = fopen($path, 'rb');
if ($fp) {
$start = max(0, $size - self::BYTES);
fseek($fp, $start);
if ($start > 0) {
fgets($fp);
}
$chunk = stream_get_contents($fp) ?: '';
fclose($fp);
$lines = preg_split('/\R/', $chunk) ?: [];
$lines = array_values(array_filter($lines, static fn ($l) => $l !== ''));
if (\count($lines) > self::LINES) {
$lines = \array_slice($lines, -self::LINES);
}
}
}
}
$json = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$json->setData(['lines' => $lines]);
return $json;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('MageSail_Magesail::tunnel')
|| $this->_authorization->isAllowed('MageSail_Magesail::tunnel_view')
|| $this->_authorization->isAllowed('MageSail_Magesail::tunnel_manage');
}
}