Passed
Push — master ( 963c04...636654 )
by Jean-Christophe
08:21
created

MultisiteSession::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 2
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Ubiquity\utils\http\session;
4
5
use Ubiquity\cache\CacheManager;
6
use Ubiquity\utils\base\UFileSystem;
7
use Ubiquity\utils\http\UCookie;
8
9
/**
10
 * Multi-sites session.
11
 * Ubiquity\utils\http\session$MultisiteSession
12
 * This class is part of Ubiquity
13
 *
14
 * @author jcheron <[email protected]>
15
 * @version 1.0.0-beta
16
 *
17
 */
18
class MultisiteSession extends AbstractSession {
19
	private $folder;
20
	private $id;
21
	const SESSION_ID = 'multi_session_id';
22
23
	private function getKey($key) {
24
		return md5 ( $key );
25
	}
26
27
	private function getFilename($key) {
28
		return $this->folder . $this->id . \DS . $this->getKey ( $key ) . '.cache.ser';
29
	}
30
31
	protected function generateId() {
32
		return \bin2hex ( \random_bytes ( 32 ) );
33
	}
34
35
	public function set($key, $value) {
36
		$val = serialize ( $value );
37
		$tmp = "/tmp/$key." . uniqid ( '', true ) . '.tmp';
38
		file_put_contents ( $tmp, $val, LOCK_EX );
39
		rename ( $tmp, $this->getFilename ( $key ) );
40
	}
41
42
	public function getAll() {
43
		$files = UFileSystem::glob_recursive ( $this->folder . \DS . '*' );
44
		$result = [ ];
45
		foreach ( $files as $file ) {
46
			$result [] = include $file;
47
		}
48
		return $result;
49
	}
50
51
	public function get($key, $default = null) {
52
		$filename = $this->getFilename ( $key );
53
		if (file_exists ( $filename )) {
54
			$f = file_get_contents ( $filename );
55
			$val = unserialize ( $f );
56
		}
57
		return isset ( $val ) ? $val : $default;
58
	}
59
60
	public function start($name = null, $root = null) {
61
		$this->name = $name;
62
		if (! isset ( $root )) {
63
			$this->folder = \ROOT . \DS . CacheManager::getCacheDirectory () . \DS . 'session' . \DS;
64
		} else {
65
			$this->folder = $root . \DS . 'session' . \DS;
66
		}
67
		if (isset ( $name )) {
68
			$this->folder .= $name . \DS;
69
		}
70
		if (! UCookie::exists ( self::SESSION_ID )) {
71
			$id = $this->generateId ();
72
			UCookie::set ( self::SESSION_ID, $id );
73
			$this->id = $id;
74
		} else {
75
			$this->id = UCookie::get ( self::SESSION_ID );
76
		}
77
		UFileSystem::safeMkdir ( $this->folder . $this->id . \DS );
78
	}
79
80
	public function exists($key) {
81
		return file_exists ( $this->getFilename ( $key ) );
82
	}
83
84
	public function terminate() {
85
		UFileSystem::delTree ( $this->folder . $this->id . \DS );
86
	}
87
88
	public function isStarted() {
89
		return isset ( $this->id );
90
	}
91
92
	public function delete($key) {
93
		unlink ( $this->getFilename ( $key ) );
94
	}
95
}
96
97