'guest']; private $cookie_options = [ 'path' => '/', 'domain' => '', 'secure' => false, 'httponly' => false, 'samesite' => 'Lax', ]; private $pending_cookies = []; private $runtime_data = null; public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } public function __construct() { $this->cookie_options['domain'] = $_SERVER['HTTP_HOST'] ?? ''; add_action('init', [$this, 'applyCookies'], 1); } public function set($key, $value, $cookie_lifetime = null) { if ($cookie_lifetime === null) { $cookie_lifetime = $this->cookie_lifetime; } $data = $this->get(); if (!is_array($data)) { $data = $this->default_data; } if ($value === null) { unset($data[$key]); } else { $data[$key] = $value; } $this->runtime_data = $data; $json_data = json_encode($data, JSON_UNESCAPED_UNICODE); if ($json_data === false) { return $this; } $this->pending_cookies[] = [ 'name' => $this->cookie_name, 'value' => $json_data, 'expires' => time() + $cookie_lifetime, ]; if (!headers_sent()) { $this->applyCookies(); } return $this; } public function get($key = null, $default = null) { if ($this->runtime_data !== null) { $data = $this->runtime_data; } elseif (isset($_COOKIE[$this->cookie_name])) { $cookie_value = wp_unslash($_COOKIE[$this->cookie_name]); $data = json_decode($cookie_value, true); if (!is_array($data)) { $data = $this->default_data; } $this->runtime_data = $data; } else { $data = $this->default_data; $this->runtime_data = $data; } return $key !== null ? ($data[$key] ?? $default) : $data; } public function has($key) { $data = $this->get(); return isset($data[$key]); } public function remove($key) { $data = $this->get(); if (isset($data[$key])) { unset($data[$key]); $this->runtime_data = $data; $json_data = json_encode($data, JSON_UNESCAPED_UNICODE); if ($json_data === false) { return $this; } $this->pending_cookies[] = [ 'name' => $this->cookie_name, 'value' => $json_data, 'expires' => time() + $this->cookie_lifetime, ]; if (!headers_sent()) { $this->applyCookies(); } } return $this; } public function clear() { $this->runtime_data = null; $this->pending_cookies[] = [ 'name' => $this->cookie_name, 'value' => '', 'expires' => time() - 3600, ]; if (!headers_sent()) { $this->applyCookies(); } return $this; } public function applyCookies() { foreach ($this->pending_cookies as $cookie) { setcookie($cookie['name'], $cookie['value'], [ 'expires' => $cookie['expires'], 'path' => $this->cookie_options['path'], 'domain' => $this->cookie_options['domain'], 'secure' => $this->cookie_options['secure'], 'httponly' => $this->cookie_options['httponly'], 'samesite' => $this->cookie_options['samesite'], ]); } $this->pending_cookies = []; } }