Passed
Push — master ( e4e152...8fde47 )
by Georgi
02:55
created

Variable   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 51
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 8 3
A put() 0 12 2
A forget() 0 10 3
A cache() 0 4 2
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