Files
MageSail/Magesail/Model/TunnelStoreState.php
T

79 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Serialize\Serializer\Json;
/**
* Persists tunnel store metadata in var/ for teardown and admin display.
*/
class TunnelStoreState
{
private const FILENAME = 'magesail_tunnel_store.json';
public function __construct(
private readonly DirectoryList $directoryList,
private readonly Json $json
) {
}
public function getFilePath(): string
{
return $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/' . self::FILENAME;
}
/**
* @return array{store_id: int, store_code: string, unsecure_base_url: string, secure_base_url: string, use_secure_urls: bool, nginx_pending_reload?: bool}|null
*/
public function read(): ?array
{
$path = $this->getFilePath();
if (!\is_readable($path)) {
return null;
}
$raw = file_get_contents($path);
if ($raw === false || trim($raw) === '') {
return null;
}
try {
/** @var array $data */
$data = $this->json->unserialize($raw);
} catch (\InvalidArgumentException) {
return null;
}
if (!isset($data['store_id'], $data['store_code'])) {
return null;
}
return [
'store_id' => (int) $data['store_id'],
'store_code' => (string) $data['store_code'],
'unsecure_base_url' => (string) ($data['unsecure_base_url'] ?? ''),
'secure_base_url' => (string) ($data['secure_base_url'] ?? ''),
'use_secure_urls' => (bool) ($data['use_secure_urls'] ?? false),
'nginx_pending_reload' => (bool) ($data['nginx_pending_reload'] ?? false),
];
}
/**
* @param array{store_id: int, store_code: string, unsecure_base_url: string, secure_base_url: string, use_secure_urls: bool, nginx_pending_reload?: bool} $data
*/
public function write(array $data): void
{
$path = $this->getFilePath();
$payload = $this->json->serialize($data);
if (file_put_contents($path, $payload, LOCK_EX) === false) {
throw new \RuntimeException('Could not write tunnel store state file.');
}
}
public function delete(): void
{
$path = $this->getFilePath();
if (\is_file($path)) {
@unlink($path);
}
}
}