<?php
/**
 * A session represents an http session
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jeroen Roos
 */

namespace web;

use settings;
use conf\conf;
use user;
use ArrayAccess;

/**
 * A session represents an http session
 *
 *
 * @package Zoph
 * @author Jeroen Roos
 */
class session implements ArrayAccess {

    /** @var holds $_SESSION variables */
    private $vars;

    /** @var holds current session */
    private static $session;

    /**
     * Create object
     */
    public function __construct(array $vars=null) {
        $this->vars=(array) $vars;
    }

    /**
     * Start the session
     * @codeCoverageIgnore
     */
    public function start() {
        ini_set("session.name", settings::$instance);
        session_set_cookie_params(conf::get("interface.cookie.expire"));
        session_start();
        static::$session=$this;
        $this->vars=&$_SESSION;
    }

    public function logout() {
        session_destroy();
        user::unsetCurrent();
    }

    /**
     * For ArrayAccess: does the offset exist
     * @param int|string offset
     * @return bool offset exists
     */
    public function offsetExists($off) {
        return (isset($this->vars[$off]));
    }

    /**
     * For ArrayAccess: Get value of parameter
     * if $_SESSION parameter is available, return it, otherwise null
     * @param int|string offset
     * @return mixed value
     */
    public function offsetGet($off) {
        if (isset($this->vars[$off])) {
            return $this->vars[$off];
        }
    }

    /**
     * For ArrayAccess: Set value of parameter
     * @param int|string offset
     * @param mixed value
     */
    public function offsetSet($off, $val) {
        $this->vars[$off]=$val;
    }

    /**
     * For ArrayAccess: Unset value of parameter
     * @param int|string offset
     */
    public function offsetUnset($off) {
        unset($this->vars[$off]);
    }

    /**
     * For ObjectAccess: Get value of parameter
     * if $_SESSION parameter is available, return it, otherwise null
     * @param int|string offset
     * @return mixed value
     */
    public function __get($off) {
        return $this->offsetGet($off);
    }

    public static function getCurrent() {
        return static::session;
    }

}
