SessionHandler.php 2.42 KB
Newer Older
Dainis Abols's avatar
Dainis Abols committed
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php

namespace Lu\LuStudyCatalogue\Domain\Session;

/**
 * Class SessionHandler
 *
 * @author  Dainis Abols <dainis.abols@lu.lv>
 * @owner   University of Latvia
 * @version 2.0.0
 * @since   25.07.2018
 *
 * @package Lu\LuStudyCatalogue\Domain\Session
 */
class SessionHandler
{
    /**
     * Keeps TYPO3 mode.
     * Either 'FE' or 'BE'.
     *
     * @var string
     */
    protected $mode = null;

    /**
     * The User-Object with the session-methods.
     * Either $GLOBALS['BE_USER'] or $GLOBALS['TSFE']->fe_user.
     *
     * @var object
     */
    protected $sessionObject = null;

    /**
     * The key the data is stored in the session.
     *
     * @var string
     */
    protected $storageKey = 'tx_lustudycatalogue';

    /**
     * Class constructor.
     *
     * @param string $mode
     *
     * @throws \Exception
     */
    public function __construct(string $mode = null)
    {
        if ($mode) {
            $this->mode = $mode;
        }

        if ($this->mode === null || ($this->mode != "BE" && $this->mode != "FE")) {
            throw new \Exception("Typo3-Mode is not defined!", 1388660107);
        }
        $this->sessionObject = ($this->mode == "BE") ? $GLOBALS['BE_USER'] : $GLOBALS['TSFE']->fe_user;
    }

    /**
     * Setter for storageKey
     *
     * @return void
     */
    public function setStorageKey($storageKey)
    {
        $this->storageKey = $storageKey;
    }

    /**
     * Store value in session
     *
     * @param string $key
     * @param mixed  $value
     *
     * @return void
     */
    public function store($key, $value)
    {
        $sessionData       = $this->sessionObject->getSessionData($this->storageKey);
        $sessionData[$key] = $value;
        $this->sessionObject->setAndSaveSessionData($this->storageKey, $sessionData);
    }

    /**
     * Delete value in session
     *
     * @param string $key
     *
     * @return void
     */
    public function delete($key)
    {
        $sessionData = $this->sessionObject->getSessionData($this->storageKey);
        unset($sessionData[$key]);
        $this->sessionObject->setAndSaveSessionData($this->storageKey, $sessionData);
    }

    /**
     * Read value from session
     *
     * @param string $key
     *
     * @return mixed
     */
    public function get($key)
    {
        $sessionData = $this->sessionObject->getSessionData($this->storageKey);

        return isset($sessionData[$key]) ? $sessionData[$key] : null;
    }
}