Passed
Push — master ( fd0d63...16794a )
by smiley
01:53
created

SessionCache   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 26
dl 0
loc 73
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 10 2
A delete() 0 6 1
A __construct() 0 14 3
A clear() 0 4 1
A get() 0 13 4
1
<?php
2
/**
3
 * Class SessionCache
4
 *
5
 * @filesource   SessionCache.php
6
 * @created      27.05.2017
7
 * @package      chillerlan\SimpleCache
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\SimpleCache;
14
15
use chillerlan\Settings\SettingsContainerInterface;
16
17
class SessionCache extends CacheDriverAbstract{
18
19
	/**
20
	 * @var string
21
	 */
22
	protected $key;
23
24
	/**
25
	 * SessionCache constructor.
26
	 *
27
	 * @param \chillerlan\Settings\SettingsContainerInterface|null $options
28
	 *
29
	 * @throws \chillerlan\SimpleCache\CacheException
30
	 */
31
	public function __construct(SettingsContainerInterface $options = null){
32
		parent::__construct($options);
33
34
		$this->key = $this->options->cacheSessionkey;
35
36
		if(!is_string($this->key) || empty($this->key)){
0 ignored issues
show
introduced by
The condition is_string($this->key) is always true.
Loading history...
37
			$msg = 'invalid session cache key';
38
39
			$this->logger->error($msg);
40
			throw new CacheException($msg);
41
		}
42
43
44
		$_SESSION[$this->key] = [];
45
	}
46
47
	/** @inheritdoc */
48
	public function get($key, $default = null){
49
		$this->checkKey($key);
50
51
		if(isset($_SESSION[$this->key][$key])){
52
53
			if($_SESSION[$this->key][$key]['ttl'] === null || $_SESSION[$this->key][$key]['ttl'] > time()){
54
				return $_SESSION[$this->key][$key]['content'];
55
			}
56
57
			unset($_SESSION[$this->key][$key]);
58
		}
59
60
		return $default;
61
	}
62
63
	/** @inheritdoc */
64
	public function set($key, $value, $ttl = null):bool{
65
		$this->checkKey($key);
66
		$ttl = $this->getTTL($ttl);
67
68
		$_SESSION[$this->key][$key] = [
69
			'ttl' => $ttl ? time() + $ttl : null,
70
			'content' => $value,
71
		];
72
73
		return true;
74
	}
75
76
	/** @inheritdoc */
77
	public function delete($key):bool{
78
		$this->checkKey($key);
79
80
		unset($_SESSION[$this->key][$key]);
81
82
		return true;
83
	}
84
85
	/** @inheritdoc */
86
	public function clear():bool{
87
		$_SESSION[$this->key] = [];
88
89
		return true;
90
	}
91
92
}
93