Files
2026-09-15 10:35:56 +08:00

77 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun3d\LanguageUrlStoreResolver\Model;
use Magento\Framework\Stdlib\Cookie\CookieMetadata;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;
class MarketCookie
{
private const STORE_COOKIE_NAME = 'store';
/**
* @var Config
*/
private $config;
/**
* @var CookieManagerInterface
*/
private $cookieManager;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
public function __construct(
Config $config,
CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory
) {
$this->config = $config;
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
}
public function get(): ?string
{
$value = $this->cookieManager->getCookie($this->config->getMarketCookieName());
return $value !== null ? trim($value) : null;
}
public function set(string $market): void
{
$metadata = $this->cookieMetadataFactory->createPublicCookieMetadata([
CookieMetadata::KEY_DURATION => $this->config->getMarketCookieLifetime(),
CookieMetadata::KEY_SAME_SITE => 'Lax',
]);
$metadata->setPath('/');
$metadata->setHttpOnly(false);
$this->cookieManager->setPublicCookie(
$this->config->getMarketCookieName(),
$market,
$metadata
);
if ($this->config->getMarketCookieName() !== self::STORE_COOKIE_NAME) {
$storeMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata([
CookieMetadata::KEY_DURATION => 31536000,
CookieMetadata::KEY_SAME_SITE => 'Lax',
]);
$storeMetadata->setPath('/');
$storeMetadata->setHttpOnly(false);
$this->cookieManager->setPublicCookie(
self::STORE_COOKIE_NAME,
$market,
$storeMetadata
);
}
}
}