82 lines
2.4 KiB
PHP
82 lines
2.4 KiB
PHP
<?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,
|
||
]);
|
||
}
|
||
}
|