|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Epesi\Core\System\Database\Models; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Collection; |
|
7
|
|
|
|
|
8
|
|
|
class Variable extends Model |
|
9
|
|
|
{ |
|
10
|
|
|
public $timestamps = false; |
|
11
|
|
|
protected $primaryKey = 'name'; |
|
12
|
|
|
protected $fillable = ['name', 'value']; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var Collection |
|
16
|
|
|
*/ |
|
17
|
|
|
private static $variables; |
|
18
|
|
|
|
|
19
|
|
|
private static function cache() { |
|
20
|
|
|
if(isset(self::$variables)) return; |
|
21
|
|
|
|
|
22
|
|
|
self::$variables = self::pluck('value', 'name'); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function get($name, $throwError = true) { |
|
26
|
|
|
self::cache(); |
|
27
|
|
|
|
|
28
|
|
|
if (! self::$variables->has($name) && $throwError) { |
|
29
|
|
|
throw new \Exception('No such variable in database: ' . $name); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
return self::$variables->get($name, ''); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public static function put($name, $value) { |
|
36
|
|
|
$maxLength = 128; |
|
37
|
|
|
|
|
38
|
|
|
if (strlen($name) > $maxLength) { |
|
39
|
|
|
throw new \Exception("Variable name too long. Max length is $maxLength."); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
self::cache(); |
|
43
|
|
|
|
|
44
|
|
|
self::$variables->put($name, $value); |
|
45
|
|
|
|
|
46
|
|
|
return self::updateOrCreate(compact('name'), compact('value')); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public static function forget($name, $throwError=true) { |
|
50
|
|
|
self::cache(); |
|
51
|
|
|
|
|
52
|
|
|
if (! self::$variables->has($name) && $throwError) { |
|
53
|
|
|
throw new \Exception('No such variable in database: ' . $name); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
self::$variables->forget($name); |
|
57
|
|
|
|
|
58
|
|
|
return self::destroy($name); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|