Bicycle/System/Classes/Cookie.php
Egor Isaev b65603b4d0 dev
2026-06-23 10:44:18 +03:00

82 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description Cookie.php
* @copyright (c) 04/06/2026
*/
namespace System\Classes;
/**
* Статический хелпер для работы с cookie.
*/
class Cookie
{
/** @var int Время жизни по умолчанию в секундах (0 — сессионная) */
public static int $expiration = 0;
/** @var string Путь cookie */
public static string $path = '/';
/** @var string|null Домен cookie */
public static ?string $domain = null;
/** @var bool Передавать только по HTTPS */
public static bool $secure = false;
/** @var bool Недоступна для JavaScript */
public static bool $httponly = true;
/** @var string Политика SameSite */
public static string $samesite = 'Lax';
/**
* @param string $key Имя cookie
* @param string|null $default Значение по умолчанию
* @return string|null
*/
public static function get(string $key, ?string $default = null): ?string
{
return $_COOKIE[$key] ?? $default;
}
/**
* Устанавливает cookie.
*
* @param string $name Имя
* @param string $value Значение
* @param int|null $lifetime Время жизни в секундах; null → self::$expiration
* @return bool
*/
public static function set(string $name, string $value, ?int $lifetime = null): bool
{
$lifetime = $lifetime ?? self::$expiration;
$expires = $lifetime > 0 ? time() + $lifetime : 0;
return setcookie($name, $value, [
'expires' => $expires,
'path' => self::$path,
'domain' => self::$domain,
'secure' => self::$secure,
'httponly' => self::$httponly,
'samesite' => self::$samesite,
]);
}
/**
* Удаляет cookie.
*
* @param string $name Имя
* @return bool
*/
public static function delete(string $name): bool
{
unset($_COOKIE[$name]);
return setcookie($name, '', [
'expires' => 1,
'path' => self::$path,
'domain' => self::$domain,
'secure' => self::$secure,
'httponly' => self::$httponly,
'samesite' => self::$samesite,
]);
}
}