summaryrefslogtreecommitdiff
path: root/include/MySession.class.php
blob: b57f7c82a5da338015ec01d7181f56c0a4dedfc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

class MySession {

  private static $_initiated = FALSE;
  private static $_dataContainer = array();

  public static function init() {
    if (!self::$_initiated) {
      session_start();
      if (!isset($_SESSION['__data'])) {
	$_SESSION['__data'] = [];
      }
      self::$_dataContainer = &$_SESSION['__data'];
    }
    self::$_initiated = TRUE;
  }
  
  private static function _getRealm() {
    $backtrace = debug_backtrace();
    while (count($backtrace) && isset($backtrace[0]['class']) && $backtrace[0]['class'] == get_class()) {
      array_shift($backtrace);
    }
    if (!count($backtrace) || (!isset($backtrace[0]['class']))) {
      throw new SessionRealmException('Session realm not provided');
    }
    return $backtrace[0]['class'];
  }

  public static function get($variable, $realm = NULL) {
    if (!self::$_initiated) {
      self::init();
    }
    if (!$realm) {
      $realm = self::_getRealm();
    }
    if (!isset(self::$_dataContainer[$realm])) {
      throw new SessionVariableException('Realm '.$realm.' doesn\'t exist');
    }
    if (!isset(self::$_dataContainer[$realm][$variable])) {
      throw new SessionVariableException('Variable '.$realm.'::'.$variable.' not set');
    }
    return self::$_dataContainer[$realm][$variable];
  }

  public static function set($variable, $value, $realm = NULL) {
    if (!self::$_initiated) {
      self::init();
    }
    if (!$realm) {
      $realm = self::_getRealm();
    }
    if (!isset(self::$_dataContainer[$realm])) {
      self::$_dataContainer[$realm] = [];
    }
    return self::$_dataContainer[$realm][$variable] = $value;
  }

}

?>