1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2014 SURFnet bv |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace Surfnet\StepupBundle\Http; |
20
|
|
|
|
21
|
|
|
use Symfony\Component\HttpFoundation\Cookie; |
22
|
|
|
use Symfony\Component\HttpFoundation\Request; |
23
|
|
|
use Symfony\Component\HttpFoundation\Response; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Read and write a given cookie from HTTP Requests/Responses. |
27
|
|
|
*/ |
28
|
|
|
final class CookieHelper |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @var Cookie |
32
|
|
|
*/ |
33
|
|
|
private $cookie; |
34
|
|
|
|
35
|
|
|
public function __construct(Cookie $cookie) |
36
|
|
|
{ |
37
|
|
|
$this->cookie = $cookie; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Write a new value for the current cookie to a given Response. |
42
|
|
|
* |
43
|
|
|
* @param string $value |
44
|
|
|
* @return Cookie |
45
|
|
|
*/ |
46
|
|
|
public function write(Response $response, $value) |
47
|
|
|
{ |
48
|
|
|
$cookie = $this->createCookieWithValue($value); |
49
|
|
|
$response->headers->setCookie($cookie); |
50
|
|
|
return $cookie; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Retrieve the current cookie from the Request if it exists. |
55
|
|
|
* |
56
|
|
|
* Note that we only read the value, we ignore the other settings. |
57
|
|
|
* |
58
|
|
|
* @param Request $request |
59
|
|
|
* @return null|Cookie |
60
|
|
|
*/ |
61
|
|
|
public function read(Request $request) |
62
|
|
|
{ |
63
|
|
|
if (!$request->cookies->has($this->cookie->getName())) { |
64
|
|
|
return null; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $this->createCookieWithValue( |
68
|
|
|
$request->cookies->get($this->cookie->getName()) |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Create a new cookie from the current (template) cookie with a new value. |
74
|
|
|
* |
75
|
|
|
* @param $value |
76
|
|
|
* @return Cookie |
77
|
|
|
*/ |
78
|
|
|
private function createCookieWithValue($value) |
79
|
|
|
{ |
80
|
|
|
return new Cookie( |
81
|
|
|
$this->cookie->getName(), |
82
|
|
|
$value, |
83
|
|
|
$this->cookie->getExpiresTime(), |
84
|
|
|
$this->cookie->getPath(), |
85
|
|
|
$this->cookie->getDomain(), |
86
|
|
|
$this->cookie->isSecure(), |
87
|
|
|
$this->cookie->isHttpOnly() |
88
|
|
|
); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|