SessionMemory.php
1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?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;
});
$factory->load(static::persistence());
}
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;
}
}