1
+ <?php
2
+
3
+ namespace Idrinth \PhpMemcachedSession \Model ;
4
+
5
+ class Session {
6
+ /**
7
+ *
8
+ * @var string
9
+ */
10
+ protected $ agent ;
11
+ /**
12
+ *
13
+ * @var \Idrinth\PhpMemcachedSession\Repository\MemCache
14
+ */
15
+ protected $ repository ;
16
+ /**
17
+ *
18
+ * @var string
19
+ */
20
+ protected $ original = '' ;
21
+ /**
22
+ *
23
+ * @var string
24
+ */
25
+ protected $ id ;
26
+ /**
27
+ *
28
+ * @var \Idrinth\PhpMemcachedSession\Model\Session
29
+ */
30
+ protected static $ instance ;
31
+ /**
32
+ *
33
+ * @param string $id
34
+ */
35
+ protected function __construct ($ id ) {
36
+ $ this ->id = $ id ;
37
+ $ this ->agent = $ this ->getUserAgent ();
38
+ $ this ->repository = new \Idrinth \PhpMemcachedSession \Repository \MemCache ();
39
+ }
40
+ /**
41
+ *
42
+ * @return string a serialized string
43
+ */
44
+ public function load () {
45
+ $ this ->original = $ this ->getByKey ([$ this ->agent ,$ this ->id ]) . '' ;
46
+ return $ this ->original ;
47
+ }
48
+ /**
49
+ *
50
+ * @param string $data
51
+ * @return boolean was it saved?
52
+ */
53
+ public function save ($ data ) {
54
+ if ($ data === $ this ->original ) {
55
+ return true ;//nothing to change
56
+ }
57
+ return $ this ->repository ->updateByKey ([$ this ->agent ,$ this ->id ],$ data );
58
+ }
59
+ /**
60
+ * deletes the current data and instance
61
+ */
62
+ public function delete () {
63
+ $ this ->repository ->removeByKey ([$ this ->agent ,$ this ->id ]);
64
+ self ::$ instance = null ;
65
+ }
66
+ /**
67
+ *
68
+ * @return string
69
+ */
70
+ private function getUserAgent () {
71
+ $ agent = $ _SERVER ['HTTP_USER_AGENT ' ];
72
+ if (strpos ($ agent ,'Opera ' ) || strpos ($ agent ,'OPR/ ' )) {
73
+ return 'opera ' ;
74
+ }
75
+ if (strpos ($ agent ,'Edge ' )) {
76
+ return 'edge ' ;
77
+ }
78
+ if (strpos ($ agent ,'Chrome ' )) {
79
+ return 'chrome ' ;
80
+ }
81
+ if (strpos ($ agent ,'Safari ' )) {
82
+ return 'safari ' ;
83
+ }
84
+ if (strpos ($ agent ,'Firefox ' )) {
85
+ return 'firefox ' ;
86
+ }
87
+ if (strpos ($ agent ,'MSIE ' ) || strpos ($ agent ,'Trident/7 ' )) {
88
+ return 'internet explorer ' ;
89
+ }
90
+ return trim (preg_replace ('/(\/|\(|[0-9]|V[0-9]).*/i ' ,'' ,$ agent ));
91
+ }
92
+ /**
93
+ *
94
+ * @param string $id
95
+ * @return \Idrinth\PhpMemcachedSession\Model\Session
96
+ */
97
+ public static function get ($ id ) {
98
+ if (!self ::$ instance ) {
99
+ self ::$ instance = new self ($ id );
100
+ }
101
+ return self ::$ instance ;
102
+ }
103
+ }
0 commit comments