<?php
/**
 * Created by PhpStorm.
 * User: jiuli
 * Date: 2018/4/7
 * Time: 下午3:20
 */

namespace Mainto\RpcServer\RpcServer\ContextTrait;

use Mainto\RpcServer\RpcServer\RpcSession;

trait SessionTrait {
    use HeaderTrait;

    /**
     * 获取当前的用户ID
     * @return null|string
     */
    public function getSessionId () {
        return $this->getHeader('X-Stream-Id');
    }

    private ?string $session_id = null;

    /**
     * @var RpcSession
     */
    private ?RpcSession $rpcSession = null;

    /**
     * 获得当前 Session
     * @return RpcSession
     */
    public function getSession () {
        if ($this->rpcSession === null) {
            if (!$this->session_id) {
                return null;
            }

            $this->rpcSession = new RpcSession($this->session_id);
            $this->rpcSession->start();
        }

        return $this->rpcSession;
    }

    /**
     * 保存当前 Session
     */
    public function saveSession () {
        if ($this->rpcSession) {
            $this->rpcSession->save();
        }
    }
}