| 1 |
<?php |
| 2 |
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly. |
| 3 |
class ESHB_Session_Manager { |
| 4 |
|
| 5 |
protected $cookie_name = 'eshb_session'; |
| 6 |
protected $cookie_lifetime = 3600; |
| 7 |
|
| 8 |
public function __construct( $cookie_name = '', $cookie_lifetime = 3600 ) { |
| 9 |
if ( ! empty( $cookie_name ) ) { |
| 10 |
$this->cookie_name = sanitize_key( $cookie_name ); |
| 11 |
} |
| 12 |
$this->cookie_lifetime = intval( $cookie_lifetime ); |
| 13 |
add_action( 'init', [ $this, 'init' ], 1 ); |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Initialize cookie if not exists |
| 18 |
*/ |
| 19 |
public function init() { |
| 20 |
if ( ! isset( $_COOKIE[ $this->cookie_name ] ) ) { |
| 21 |
$this->set_cookie_data( [] ); |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Set entire session data as array |
| 27 |
*/ |
| 28 |
protected function set_cookie_data( $data ) { |
| 29 |
if ( ! headers_sent() ) { |
| 30 |
setcookie( $this->cookie_name, json_encode( $data ), time() + $this->cookie_lifetime, '/' ); |
| 31 |
} |
| 32 |
$_COOKIE[ $this->cookie_name ] = json_encode( $data ); // for immediate access |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Get full session data |
| 37 |
*/ |
| 38 |
public function all() { |
| 39 |
return isset( $_COOKIE[ $this->cookie_name ] ) |
| 40 |
? json_decode( sanitize_textarea_field( wp_unslash( $_COOKIE[ $this->cookie_name ] ) ), true ) |
| 41 |
: []; |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
/** |
| 46 |
* Get a value by key |
| 47 |
*/ |
| 48 |
public function get( $key, $default = null ) { |
| 49 |
$data = $this->all(); |
| 50 |
return $data[$key] ?? $default; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Set a value by key |
| 55 |
*/ |
| 56 |
public function set( $key, $value ) { |
| 57 |
$data = $this->all(); |
| 58 |
$data[$key] = $value; |
| 59 |
$this->set_cookie_data( $data ); |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Remove a key from session |
| 64 |
*/ |
| 65 |
public function remove( $key ) { |
| 66 |
$data = $this->all(); |
| 67 |
unset( $data[$key] ); |
| 68 |
$this->set_cookie_data( $data ); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Clear all session data |
| 73 |
*/ |
| 74 |
public function clear() { |
| 75 |
$this->set_cookie_data( [] ); |
| 76 |
} |
| 77 |
} |
| 78 |
|