|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ElePHPant\Cookie\Storage; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* Class CookieStorage |
|
8
|
|
|
* |
|
9
|
|
|
* Please report bugs on https://github.com/wilderamorim/cookie/issues |
|
10
|
|
|
* |
|
11
|
|
|
* @author Wilder Amorim <https://github.com/wilderamorim> |
|
12
|
|
|
* @link https://www.linkedin.com/in/wilderamorim/ |
|
13
|
|
|
*/ |
|
14
|
|
|
class CookieStorage implements CookieStorageInterface |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Set a cookie. |
|
18
|
|
|
* |
|
19
|
|
|
* @param string $name The name of the cookie. |
|
20
|
|
|
* @param string|null $value The value of the cookie. |
|
21
|
|
|
* @param int $expire The expiration time of the cookie as a Unix timestamp. |
|
22
|
|
|
* @param string|null $path The path on the server in which the cookie will be available. |
|
23
|
|
|
* @return bool True if the cookie is set successfully, false otherwise. |
|
24
|
|
|
*/ |
|
25
|
|
|
public function set(string $name, ?string $value, int $expire, ?string $path = null): bool |
|
26
|
|
|
{ |
|
27
|
|
|
return setcookie($name, $value, $expire, ($path ?? '/')); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Get the value of a cookie or all cookies. |
|
32
|
|
|
* |
|
33
|
|
|
* @param string|null $name The name of the cookie. If null, returns an array of all cookies. |
|
34
|
|
|
* @return mixed The value of the cookie or an array of all cookies. |
|
35
|
|
|
*/ |
|
36
|
|
|
public function get(?string $name = null) |
|
37
|
|
|
{ |
|
38
|
|
|
if (!$name) { |
|
39
|
|
|
return filter_input_array(INPUT_COOKIE, FILTER_DEFAULT); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
return filter_input(INPUT_COOKIE, $name, FILTER_DEFAULT); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Delete a cookie or all cookies. |
|
47
|
|
|
* |
|
48
|
|
|
* @param string|null $name The name of the cookie. If null, deletes all cookies. |
|
49
|
|
|
* @param string|null $path The path on the server in which the cookie was available. |
|
50
|
|
|
* @return bool True if the cookie(s) is deleted successfully, false otherwise. |
|
51
|
|
|
*/ |
|
52
|
|
|
public function delete(?string $name = null, ?string $path = null): bool |
|
53
|
|
|
{ |
|
54
|
|
|
if (!$name) { |
|
55
|
|
|
array_map(fn($name) => $this->set($name, null, -1, $path), array_keys($_COOKIE)); |
|
56
|
|
|
return true; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
return $this->set($name, null, -1, $path); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|