<?php

namespace Vn\Web;

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

	function close ()
	{
		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;
	}

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

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

	function write ($sessionId, $sessionData)
	{
		$this->db->query ('REPLACE INTO userSession SET ssid = #, data = #',
			[$sessionId, $sessionData]);
		//$db->query ('DO RELEASE_LOCK(#)', [$sessionId]);
		return TRUE;
	}
}

?>
