SessionMemory.php 2.0 KB
<?php

namespace Lackoxygen\TiktokShop\Supervisor\Session;

use Lackoxygen\TiktokShop\Contracts\SessionInterface;

class SessionMemory
{
    /**
     * @var Session [] $sessions
     */
    protected static array $sessions = [];

    /**
     * @var string
     */
    protected static string $cachePrefix = 'tiktok.shop:session:';


    protected static function cache()
    {
        static $cacheManager;
        if (is_null($cacheManager)) {
            $cacheManager = app('cache');
        }

        return $cacheManager;
    }

    public static function init()
    {
        $factory = new Factory(function (Session $session) {
            static::$sessions[$session->appKey()] = $session;
        });

        if ($raw = static::persistence()) {
            $factory->load($raw);
        }
    }

    public static function persistence()
    {
        $key = static::$cachePrefix . 'keepalive_table';
        try {
            if (func_get_args()) {
                static::cache()->set($key, func_get_arg(0));
            } else {
                $raw = static::cache()->get($key);

                if (is_null($raw)) {
                    return null;
                }

                return $raw;
            }
        } catch (\Exception $e) {
        }
    }

    public static function each(\Closure $callback)
    {
        foreach (static::$sessions as $session) {
            $callback($session);
        }
    }

    public static function get(string $appKey = null)
    {
        if (is_null($appKey)) {
            return static::$sessions;
        }

        return static::exist($appKey) ? static::$sessions[$appKey] : null;
    }

    public static function exist(string $appKey): bool
    {
        return array_key_exists($appKey, static::$sessions);
    }

    public static function put(SessionInterface $session, $force = true)
    {
        if (static::exist($session->appKey()) && !$force) {
            return;
        }
        static::$sessions[$session->appKey()] = $session;
    }
}