<?php namespace sc;

class Session
{
    /** @var string COOKIE名称 */
    private $cookieName = 'sem-cms_cookie_session';
    /** @var int COOKIE过期时间 */
    private $cookieExpire = 0;
    /** @var string COOKIE作用路径 */
    private $cookiePath = '/';
    /** @var string COOKIE作用域名 */
    private $cookieDomain = '';
    /** @var bool COOKIE安全连接保存 */
    private $cookieSecure = false;
    /** @var string SESSION保存方式 */
    private $dirver = 'files';
    /** @var string SESSION保存路径 */
    private $savePath = null;

    /**
     * Session constructor.
     * 属性赋值
     *
     * @param array $conf
     */
    public function __construct($conf)
    {
        foreach ($conf as $index => $value) {
            $index = preg_replace_callback('/(_)([a-z])/', function ($matches) {
                return strtoupper($matches[2]);
            }, $index);

            $this->$index = $value;
        }
    }

    /**
     * 启用SESSION
     */
    public function start()
    {
        $this->configure();

        if ((bool)ini_get('session.auto_start')) {
            return;
        }

        if (PHP_SESSION_ACTIVE == session_status()) {
            return;
        }

        session_start();
    }

    /**
     * 停用SESSION
     */
    public function stop()
    {
        $this->clean();
        setcookie($this->cookieName, session_id(), 1, $this->cookiePath, $this->cookieDomain, $this->cookieSecure, false);
    }

    /**
     * 清理SESSION
     */
    public function destroy()
    {
        session_destroy();
    }

    /**
     * 删除SESSION
     *
     * @param string $index
     *
     * @return mixed
     */
    public function remove($index)
    {
        $value = isset($_SESSION[$index]) ? $_SESSION[$index] : null;
        unset($_SESSION[$index]);
        return $value;
    }

    /**
     * 清空SESSION
     */
    public function clean()
    {
        session_unset();
    }

    /**
     * 获取SESSION
     *
     * @param string $index
     *
     * @return mixed
     */
    public function get($index)
    {
        return isset($_SESSION[$index]) ? $_SESSION[$index] : null;
    }

    /**
     * 保存SESSION
     *
     * @param string $index
     * @param mixed $value
     */
    public function set($index, $value)
    {
        $_SESSION[$index] = $value;
    }

    /**
     * 配置SESSION
     */
    private function configure()
    {
        if (null != $this->cookieName) {
            ini_set('session.name', $this->cookieName);
        }

        session_set_cookie_params($this->cookieExpire, $this->cookiePath, $this->cookieDomain, $this->cookieSecure, false);

        if (null != $this->savePath) {
            session_save_path($this->savePath);
        }
    }
}