1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Epesi\Core\System\Model; |
4
|
|
|
|
5
|
|
|
use atk4\data\Model; |
6
|
|
|
use Epesi\Core\Data\HasEpesiConnection; |
7
|
|
|
use Illuminate\Database\Eloquent\Collection; |
8
|
|
|
|
9
|
|
|
class Variable extends Model |
10
|
|
|
{ |
11
|
|
|
use HasEpesiConnection; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var Collection |
15
|
|
|
*/ |
16
|
|
|
private static $variables; |
17
|
|
|
|
18
|
|
|
public $table = 'variables'; |
19
|
|
|
|
20
|
|
|
public $strict_types = false; |
21
|
|
|
|
22
|
|
|
private static function cache() { |
23
|
|
|
if(isset(self::$variables)) return; |
24
|
|
|
|
25
|
|
|
self::$variables = self::pluck('value', 'name'); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
protected function init(): void |
29
|
|
|
{ |
30
|
|
|
parent::init(); |
31
|
|
|
|
32
|
|
|
$this->addFields([ |
33
|
|
|
'name', |
34
|
|
|
'value' => ['type' => 'text', 'serialize' => 'json'] |
35
|
|
|
]); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public static function recall($name, $default = null) { |
39
|
|
|
self::cache(); |
40
|
|
|
|
41
|
|
|
if (!self::$variables->has($name)) return $default; |
42
|
|
|
|
43
|
|
|
return self::$variables->get($name, $default) ?? $default; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public static function memorize($name, $value) { |
47
|
|
|
$maxLength = 128; |
48
|
|
|
|
49
|
|
|
if (strlen($name) > $maxLength) { |
50
|
|
|
throw new \Exception("Variable name too long. Max length is $maxLength."); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
self::cache(); |
54
|
|
|
|
55
|
|
|
self::$variables->put($name, $value); |
56
|
|
|
|
57
|
|
|
$variable = self::create()->addCondition('name', $name)->tryLoadAny(); |
58
|
|
|
|
59
|
|
|
if ($variable->loaded()) { |
60
|
|
|
$variable->save(compact('value')); |
61
|
|
|
} |
62
|
|
|
else { |
63
|
|
|
$variable->insert(compact('name', 'value')); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public static function forget($name, $throwError=true) { |
68
|
|
|
self::cache(); |
69
|
|
|
|
70
|
|
|
if (!self::$variables->has($name) && $throwError) { |
71
|
|
|
throw new \Exception('No such variable in database: ' . $name); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
self::$variables->forget($name); |
75
|
|
|
|
76
|
|
|
return self::create()->addCondition('name', $name)->tryLoadAny()->delete(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|