Completed
Push — master ( 597177...94412d )
by Timo
04:45
created

SessionHelper::getState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace hamburgscleanest\DataTables\Helpers;
4
5
use Illuminate\Http\Request;
6
7
/**
8
 * Class SessionHelper
9
 * @package hamburgscleanest\DataTables\Helpers
10
 */
11
class SessionHelper {
12
13
    const SESSION_STORAGE = 'data-tables.';
14
15
    /** @var Request */
16
    private $_request;
17
18
    /**
19
     * SessionHelper constructor.
20
     * @param Request $request
21
     */
22 31
    public function __construct(Request $request)
1 ignored issue
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
23
    {
24 31
        $this->_request = $request;
25 31
    }
26
27
    /**
28
     * Save the state for the given key.
29
     *
30
     * @param string $key
31
     * @param mixed $sessionValue
32
     */
33 2
    public function saveState(string $key, $sessionValue)
34
    {
35 2
        $this->_request->session()->put($this->_getFormattedKey($key), $sessionValue);
36 2
    }
37
38
    /**
39
     * @param string $key
40
     * @return string
41
     */
42 3
    private function _getFormattedKey(string $key) : string
43
    {
44
        return
45 3
            self::SESSION_STORAGE .
46 3
            \preg_replace(
47 3
                '/\.|\//',
48 3
                '_',
49 3
                \preg_replace('/(http|https):\/\//', '', $this->_request->url())
50
            ) .
51 3
            '.' . $key;
52
    }
53
54
    /**
55
     * Get the state for the given key.
56
     *
57
     * @param string $key
58
     * @param null $default
59
     * @return mixed
60
     */
61 3
    public function getState(string $key, $default = null)
62
    {
63 3
        return $this->_request->session()->get($this->_getFormattedKey($key)) ?? $default;
64
    }
65
66
    /**
67
     * Remove the state for the given key.
68
     *
69
     * @param string $key
70
     */
71 1
    public function removeState(string $key)
72
    {
73 1
        $this->_request->session()->remove($this->_getFormattedKey($key));
74
    }
75
}