Files
MageSail/Magesail/Model/TunnelRequestDetector.php
T
2026-03-21 03:01:08 -05:00

67 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Model;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Api\StoreRepositoryInterface;
/**
* Detects MageSail tunnel proxy (header / query / server / hostname vs persisted tunnel URLs) on the request.
*/
class TunnelRequestDetector
{
private const HEADER_STORE_CODE = 'X-MageSail-Store-Code';
private const QUERY_PARAM_STORE = 'magesail_store';
private const SERVER_HEADER = 'HTTP_X_MAGESAIL_STORE_CODE';
public function __construct(
private readonly TunnelHostnameMatcher $tunnelHostnameMatcher,
private readonly StoreRepositoryInterface $storeRepository
) {
}
public function getTunnelStoreCode(Http $request): ?string
{
$value = $request->getParam(self::QUERY_PARAM_STORE);
if ($value !== null && trim((string) $value) !== '') {
return $this->onlyIfStoreExists(trim((string) $value));
}
$value = $request->getHeader(self::HEADER_STORE_CODE);
if ($value !== false && $value !== null && trim((string) $value) !== '') {
return $this->onlyIfStoreExists(trim((string) $value));
}
$value = $request->getServer(self::SERVER_HEADER);
if ($value !== null && $value !== '' && trim((string) $value) !== '') {
return $this->onlyIfStoreExists(trim((string) $value));
}
$uri = (string) $request->getRequestUri();
if ($uri !== '' && str_contains($uri, self::QUERY_PARAM_STORE . '=')) {
$query = str_contains($uri, '?') ? substr($uri, strpos($uri, '?') + 1) : '';
parse_str($query, $params);
$v = $params[self::QUERY_PARAM_STORE] ?? '';
if ($v !== '' && trim((string) $v) !== '') {
return $this->onlyIfStoreExists(trim((string) $v));
}
}
return $this->onlyIfStoreExists(
$this->tunnelHostnameMatcher->getStoreCodeIfRequestHostMatchesState($request)
);
}
private function onlyIfStoreExists(?string $code): ?string
{
if ($code === null || $code === '') {
return null;
}
try {
$this->storeRepository->get($code);
return $code;
} catch (NoSuchEntityException) {
return null;
}
}
}