Test Failed
Push — master ( 8f2167...5d2217 )
by Georgi
08:27
created

Variable   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
dl 0
loc 75
rs 10
c 1
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A cache() 0 4 2
A recall() 0 6 2
A memorize() 0 18 3
A init() 0 14 2
A forget() 0 10 3
1
<?php
2
3
namespace Epesi\Core\System\Models;
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
	public function init() {
29
	    parent::init();
30
	    
31
	    $this->addFields([
32
	            'name',
33
	            'value' => ['type' => 'text']
34
	    ]);
35
36
	    $this->addHook('beforeSave', function(Variable $variable) {
37
	        $variable['value'] = json_encode($variable['value']);
38
	    });
39
	    
40
	    $this->addHook('beforeLoad', function(Variable $variable) {
41
	        $variable['value'] = $variable['value']? json_decode($variable['value']): '';
42
	    });
43
	}
44
	
45
	public static function recall($name, $default = null) {
46
		self::cache();
47
		
48
		if (! self::$variables->has($name)) return $default;
49
		
50
		return self::$variables->get($name, $default)?? $default;
51
	}
52
	
53
	public static function memorize($name, $value) {
54
		$maxLength = 128;
55
		
56
		if (strlen($name) > $maxLength) {
57
			throw new \Exception("Variable name too long. Max length is $maxLength.");
58
		}
59
		
60
		self::cache();
61
		
62
		self::$variables->put($name, $value);
63
		
64
		$variable = self::create()->addCondition('name', $name)->tryLoadAny();
65
		
66
		if ($variable->loaded()) {
67
		    $variable->save(compact('value'));
68
		}
69
		else {
70
		    $variable->insert(compact('name', 'value'));
71
		}
72
	}
73
	
74
	public static function forget($name, $throwError=true) {
75
		self::cache();
76
		
77
		if (! self::$variables->has($name) && $throwError) {
78
			throw new \Exception('No such variable in database: ' . $name);
79
		}
80
		
81
		self::$variables->forget($name);
82
			
83
		return self::create()->addCondition('name', $name)->tryLoadAny()->delete();
84
	}
85
}
86