Session.php 1.89 KB
Newer Older
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 5/4/16
 * Time: 1:34 PM
 */

namespace qfq;


class Session {
    private static $instance = null;
    private static $phpUnit = null;
    private static $sessionLocal = array();

    /**
     * @param bool|false $phpUnit
     */
    private function __construct($phpUnit = false) {
        if (self::$phpUnit !== null)
            throw new CodeException("Try to set flag phpunit again - that should not happen.", ERROR_CODE_SHOULD_NOT_HAPPEN);

        self::$phpUnit = $phpUnit;

        if (self::$phpUnit) {
            self::$sessionLocal = array();
        } else {
            session_name();
            session_start();
        }
    }

    /**
     * @param bool|false $phpUnit
     * @return null|\qfq\Store
     */
    public static function getInstance($phpUnit = false) {

        // Design Pattern: Singleton
        if (self::$instance === null) {
            self::$instance = new self($phpUnit);
        }

        return self::$instance;
    }

    /**
     * @param $key
     * @return bool
     */
    public static function get($key) {

        if (self::$phpUnit) {
            if (isset(self::$sessionLocal[$key]))
                $value = self::$sessionLocal[$key];
            else
                $value = false;
        } else {
            if (isset($_SESSION[$key]))
                $value = $_SESSION[$key];
            else
                $value = false;

        }

        return $value;
    }

    /**
     * @param $key
     * @param $value
     */
    public static function set($key, $value) {

        if (self::$phpUnit) {
            self::$sessionLocal[$key] = $value;
        } else {
            $_SESSION[$key] = $value;
        }
    }

    /**
     */
    public static function clear() {

        if (self::$phpUnit) {
            self::$sessionLocal = array();
        } else {
            unset($_SESSION);
        }
    }

}