<?php

namespace Vn\Web;

class DbSessionHandler implements \SessionHandlerInterface
{
	private $db;
	
	function __construct ($db)
	{
		$this->db = $db;
	}

	function open ($savePath, $name)
	{
		return TRUE;
	}

	function close ()
	{
		return TRUE;
	}

	function read ($sessionId)
	{
		$sessionData = $this->db->getValue (
			'SELECT data FROM userSession WHERE ssid = #', [$sessionId]);
		return isset ($sessionData) ? $sessionData : '';
	}

	function write ($sessionId, $sessionData)
	{
		$this->db->query (
			'INSERT INTO userSession SET
					ssid = #, data = #, lastUpdate = NOW()
				ON DUPLICATE KEY UPDATE
					data = VALUES(data), lastUpdate = VALUES(lastUpdate)',
			[$sessionId, $sessionData]);
		return TRUE;
	}

	function destroy ($sessionId)
	{
		$this->db->query ('DELETE FROM userSession WHERE ssid = #', [$sessionId]);
		return TRUE;	
	}

	function gc ($maxLifeTime)
	{
		$this->db->query ('DELETE FROM userSession
			WHERE lastUpdate < TIMESTAMPADD(SECOND, -#, NOW())',
			[$maxLifeTime]
		);
		return TRUE;
	}
}
