-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCookieProvider.php
108 lines (97 loc) · 2.94 KB
/
CookieProvider.php
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
<?php
namespace NPR\One\Providers;
use NPR\One\Interfaces\StorageInterface;
/**
* A thin wrapper around the PHP functions to get and set cookies. Useful for unit testing.
*
* @package NPR\One\Providers
*/
class CookieProvider implements StorageInterface
{
/** @var null|string - the domain to use for the cookies
* @internal */
private $domain = null;
/** @var string - the key prefix use for the cookies
* @internal */
public $keyPrefix = '';
/**
* Sets a cookie value for the given name
*
* @param string $key
* @param string $value
* @param null|int $expiresIn
* @codeCoverageIgnore
*/
public function set($key, $value, $expiresIn = null)
{
if (isset($expiresIn))
{
$expiresIn += time();
}
setcookie($this->keyPrefix . $key, $value, $expiresIn, '/', $this->domain);
}
/**
* Get the value of cookie by given name
*
* @param string $key
* @return string|null
* @codeCoverageIgnore
*/
public function get($key): ?string
{
return isset($_COOKIE[$this->keyPrefix . $key]) ? $_COOKIE[$this->keyPrefix . $key] : null;
}
/**
* {@inheritdoc}
*
* @codeCoverageIgnore
*/
public function compare($key, $value): bool
{
return $this->get($key) === $value;
}
/**
* Removes the cookie if one exists
*
* @param string $key
* @codeCoverageIgnore
*/
public function remove($key)
{
if (isset($_COOKIE[$this->keyPrefix . $key]))
{
unset($_COOKIE[$this->keyPrefix . $key]);
setcookie($this->keyPrefix . $key, '', time() - 3600, '/'); // empty value and old timestamp
}
}
/**
* Sets the domain to use for the cookies.
*
* @param null|string $domain
* @throws \InvalidArgumentException if the passed-in value is not either a non-empty string, or null
*/
public function setDomain($domain = null)
{
if (!($domain === null || (!empty($domain) && is_string($domain))))
{
throw new \InvalidArgumentException('If set, the cookie domain must be a string; otherwise, it should be null');
}
$this->domain = $domain;
}
/**
* If you have multiple proxies living on one server and are using the same cookie domain, you may need to be able
* to use a prefix to differentiate between them. Use this function in that case.
* (By default, this should not be needed, and the prefix is initially set to an empty string.)
*
* @param string $prefix
* @throws \InvalidArgumentException if the passed-in value is not a string
*/
public function setKeyPrefix($prefix = '')
{
if (!is_string($prefix))
{
throw new \InvalidArgumentException('The cookie prefix should always be a string, even if it is an empty one.');
}
$this->keyPrefix = $prefix;
}
}