1: <?php
2:
3: namespace PHPixie\HTTP\Context\Session;
4:
5: /**
6: * Standard PHP session storage
7: */
8: class SAPI implements \PHPixie\HTTP\Context\Session
9: {
10: /**
11: * Session array by reference
12: * @var array
13: */
14: protected $sessionReference;
15:
16: /**
17: * @var bool
18: */
19: protected $sessionStarted = false;
20:
21: /**
22: * @inheritdoc
23: */
24: public function id()
25: {
26: $this->requireSession();
27: return $this->sessionId();
28: }
29:
30: /**
31: * @inheritdoc
32: */
33: public function setId($id)
34: {
35: $this->sessionId($id);
36: $this->sessionStarted = false;
37: }
38:
39: /**
40: * @inheritdoc
41: */
42: public function get($key, $default = null)
43: {
44: if($this->exists($key)) {
45: return $this->sessionReference[$key];
46: }
47:
48: return $default;
49: }
50:
51: /**
52: * @inheritdoc
53: */
54: public function getRequired($key)
55: {
56: if($this->exists($key)) {
57: return $this->sessionReference[$key];
58: }
59:
60: throw new \PHPixie\HTTP\Exception("Session variable '$key' is not set");
61: }
62:
63: /**
64: * @inheritdoc
65: */
66: public function exists($key)
67: {
68: $this->requireSession();
69: return array_key_exists($key, $this->sessionReference);
70: }
71:
72: /**
73: * @inheritdoc
74: */
75: public function set($key, $value)
76: {
77: $this->requireSession();
78: $this->sessionReference[$key] = $value;
79: }
80:
81: /**
82: * @inheritdoc
83: */
84: public function remove($key)
85: {
86: $this->requireSession();
87: unset($this->sessionReference[$key]);
88: }
89:
90: /**
91: * @inheritdoc
92: */
93: public function asArray()
94: {
95: $this->requireSession();
96: return $this->sessionReference;
97: }
98:
99: /**
100: * @return void
101: */
102: protected function requireSession()
103: {
104: if($this->sessionStarted === true) {
105: return;
106: }
107:
108: $this->sessionStart();
109: $this->sessionStarted = true;
110: $this->sessionReference = &$this->session();
111: }
112:
113: /**
114: * Refrence to the $_SESSION array
115: * @return array
116: */
117: protected function &session()
118: {
119: return $_SESSION;
120: }
121:
122: /**
123: * @return void
124: */
125: protected function sessionStart()
126: {
127: session_start();
128: }
129:
130: /**
131: * @param string|null $id
132: * @return string
133: */
134: protected function sessionId($id = null)
135: {
136: if($id === null) {
137: return session_id();
138:
139: }else{
140: return session_id($id);
141: }
142: }
143: }