<?php
namespace Helper;
use Bitrix\Main\Application;
use Bitrix\Main\Web\Cookie;
class CookieHelper
{
/**
* selected_warehouse - выбранный склад
* selected_warehouse_title - название склада
* delivery_method - способ получения
* delivery_address - адрес доставки
* // delivery_time - время доставки
*/
public static function set(string $name, string $value, bool $remove = false): void
{
$application = Application::getInstance();
$context = $application->getContext();
if(!$remove) {
$cookie = new Cookie($name, serialize($value), time() + (365 * 24 * 60 * 60));
} else {
$cookie = new Cookie($name, '', time() - 3600);
}
$cookie->setDomain($context->getServer()->getServerName());
$context->getResponse()->addCookie($cookie);
$context->getResponse()->writeHeaders(); // При установке через AJAX без пролога.
}
public static function get(string $name, $needUnserialize = true):string | null
{
$result = Application::getInstance()
->getContext()
->getRequest()
->getCookie($name)
;
if ($result === null) {
return null;
}
if ($needUnserialize) {
$resultUnserialized = @unserialize($result, ["CookieHelper"]);
if($resultUnserialized !== false) {
return $resultUnserialized;
}
}
return $result;
}
public static function unsetStore(string $deliveryMethod = ''):void
{
self::set('selected_warehouse', '', true);
self::set('selected_warehouse_title', '', true);
if ($deliveryMethod === '') {
self::set('delivery_method', '', true);
} else {
self::set('delivery_method', $deliveryMethod);
}
}
public static function unsetDelivery(string $deliveryMethod = ''):void
{
self::set('delivery_address', '', true);
if ($deliveryMethod === '') {
self::set('delivery_method', '', true);
} else {
self::set('delivery_method', $deliveryMethod);
}
}
public static function resetAllDeliveryCookies():void
{
self::set('selected_warehouse', '', true);
self::set('selected_warehouse_title', '', true);
self::set('delivery_method', '', true);
self::set('delivery_address', '', true);
}
}