'guest']; // Default data private $cookie_options = [ 'path' => '/', 'domain' => '', 'secure' => false, 'httponly' => true, 'samesite' => 'Lax' ]; private $pending_cookies = []; // Store cookies to set later 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'] ?? ''; // Hook into WordPress to set cookies add_action('init', [$this, 'applyCookies']); } public function set($key, $value, $cookie_lifetime = null) { if (empty($cookie_lifetime)) { $cookie_lifetime = $this->cookie_lifetime; } $data = $this->get() ?? $this->default_data; if (!is_array($data)) { $data = $this->default_data; } $data[$key] = $value; $json_data = json_encode($data, JSON_UNESCAPED_UNICODE); if ($json_data === false) { return $this; } // Store cookies to apply during `init` $this->pending_cookies[] = [ 'name' => $this->cookie_name, 'value' => $json_data, 'expires' => time() + $cookie_lifetime, ]; return $this; // Allows method chaining } 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'], ]); } // Clear pending cookies $this->pending_cookies = []; } public function get($key = null, $default = null) { if (!isset($_COOKIE[$this->cookie_name])) { return $key === null ? $this->default_data : $default; } $cookie_value = wp_unslash($_COOKIE[$this->cookie_name]); $data = json_decode($cookie_value, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) { return $key === null ? $cookie_value : $default; } 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]); $json_data = json_encode($data, JSON_UNESCAPED_UNICODE); if ($json_data === false) { error_log('JSON encoding failed: ' . json_last_error_msg()); return $this; } $this->set($key, null, -3600); // Mark cookie for immediate expiry } return $this; } public function clear() { $this->set($this->cookie_name, '', -3600); // Set expiry in the past return $this; } }