Files
MageSail/Magesail/Block/Adminhtml/Tunnel.php
T
2026-03-12 17:05:22 -05:00

82 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Block\Adminhtml;
use Magento\Backend\Block\Template;
use MageSail\Magesail\Model\TunnelStatus;
class Tunnel extends Template
{
private const LOG_TAIL_BYTES = 8192;
private const LOG_TAIL_LINES = 40;
public function __construct(
Template\Context $context,
private readonly TunnelStatus $tunnelStatus,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array{running: bool, pid: int|null, key: string|null}
*/
public function getTunnelStatus(): array
{
return $this->tunnelStatus->getStatus();
}
public function getConfigUrl(): string
{
return $this->getUrl('adminhtml/system_config/edit/section/magesail');
}
public function getStatusUrl(): string
{
return $this->getUrl('*/*/status', ['_query' => ['form_key' => $this->getFormKey()]]);
}
public function getFormKey(): string
{
return $this->formKey->getFormKey();
}
public function getLogFilePath(): string
{
return $this->tunnelStatus->getLogFilePath();
}
/**
* @return string[]
*/
public function getRecentLogLines(): array
{
$path = $this->tunnelStatus->getLogFilePath();
if (!\is_readable($path)) {
return [];
}
$size = filesize($path);
if ($size === false || $size === 0) {
return [];
}
$fp = fopen($path, 'rb');
if ($fp === false) {
return [];
}
$start = max(0, $size - self::LOG_TAIL_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::LOG_TAIL_LINES) {
$lines = \array_slice($lines, -self::LOG_TAIL_LINES);
}
return $lines;
}
}