Cookie::set()   B
last analyzed

Complexity

Conditions 9
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 20
rs 8.0555
c 0
b 0
f 0
cc 9
nc 2
nop 0
1
<?php
2
/**
3
 * KNUT7 K7F (https://marciozebedeu.com/)
4
 * KNUT7 K7F (tm) : Rapid Development Framework (https://marciozebedeu.com/).
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @see      https://github.com/knut7/framework/ for the canonical source repository
11
 *
12
 * @copyright (c) 2015.  KNUT7  Software Technologies AO Inc. (https://marciozebedeu.com/)
13
 * @license   https://marciozebedeu.com/license/new-bsd New BSD License
14
 * @author    Marcio Zebedeu - [email protected]
15
 *
16
 * @version   1.0.2
17
 */
18
19
namespace Ballybran\Helpers\Http;
20
use Ballybran\Core\Http\{Request , Response , RestUtilities};
21
22
23
/**
24
 * Class Cookie.
25
 */
26
class Cookie
27
{
28
29
    private static $default = [
30
        'name'=> null,
31
        'value'=>null,
32
        'maxage' => null,
33
        'expire' => null,
34
        'path' => null,
35
        'domain' => null,
36
        'secure' => false,
37
        'HTTPOnly' => false
38
    ];
39
40
    private $data;
41
    private $request;
0 ignored issues
show
introduced by
The private property $request is not used, and could be removed.
Loading history...
42
    private $response;
0 ignored issues
show
introduced by
The private property $response is not used, and could be removed.
Loading history...
43
    private $responseCode;
44
45
46
    public function __construct()
47
    {
48
        $this->data = self::$default;
49
    }
50
51
    /**
52
     * @param $name
53
     * @param int $maxage time in second, for example : 60 = 1min
54
     * @param string $path
55
     * @param string $domain
56
     * @param bool $secure
57
     * @param bool $HTTPOnly
58
     *
59
     * @return Cookie
60
     */
61
    public function createCookie($name, int $maxage = 0, string $path = '', string $domain = '', bool $secure = false, bool $HTTPOnly = false): Cookie
62
    {
63
        $this->setName($name)
64
        ->setMaxage($maxage)
65
        ->setPath($path)
66
        ->setDomain($domain)
67
        ->setSecure($secure)
68
        ->setHTTPOnly($HTTPOnly);
69
70
        return $this->set();
71
    }
72
73
    public function set(): Cookie
74
    {
75
        $ob = ini_get('output_buffering');
76
77
        // Abort the method if headers have already been sent, except when output buffering has been enabled
78
        if (headers_sent() && false === (bool)$ob || 'off' == strtolower($ob)) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (headers_sent() && false...off' == strtolower($ob), Probably Intended Meaning: headers_sent() && (false...ff' == strtolower($ob))
Loading history...
79
            return $this;
80
        }
81
82
//         Prevent "headers already sent" error with utf8 support (BOM)
83
//        if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');
84
        header('Set-Cookie: ' . $this->getName() . ";"
85
            . (empty($this->getDomain()) ? '' : '; Domain=' . $this->getDomain())
86
            . (empty($this->getMaxage()) ? '' : '; Max-Age=' . $this->getMaxage())
87
            . (empty($this->getPath()) ? '' : '; Path=' . $this->getPath())
88
            . (!$this->getSecure() ? '' : '; Secure')
89
            . (!$this->getHTTPOnly() ? '' : '; HttpOnly'), false, $this->getResponseCode());
90
91
92
        return $this;
93
    }
94
95
    /**
96
     * Get the value of maxage.
97
     */
98
    private function getMaxage() : int
99
    {
100
        return $this->data['maxage'];
101
    }
102
103
    /**
104
     * Set the value of maxage.
105
     *
106
     */
107
    public function setMaxage($maxage) : Cookie
108
    {
109
110
        if (!is_null($maxage)) {
111
            $maxage = intval($maxage);
112
            $this->data['maxage'] = 'Expires=' .gmdate("D, d M Y H:i:s",  $maxage > 0 ? time() + $maxage : 0)." GMT" . 'Max-Age=' . $maxage;
113
        }
114
        $this->data['maxage'] = $maxage;
115
        return $this;
116
117
    }
118
119
    /**
120
     * Get the value of name.
121
     */
122
    private function getName() : string
123
    {
124
        return $this->data['name'];
125
    }
126
127
    /**
128
     * Set the value of name.
129
     *
130
     */
131
    public function setName($name) : Cookie
132
    {
133
        if (is_array($name)) {
134
135
            foreach ($name as $k => $v) {
136
                $this->data['name'] = $k . '=' . rawurlencode($v);
137
            }
138
        } else {
139
            $this->data['name'] = $name . '=' . rawurlencode($name);
140
        }
141
142
        return $this;
143
144
    }
145
146
    /**
147
     * Get the value of path.
148
     */
149
    private function getPath() : string
150
    {
151
        return $this->data['path'];
152
    }
153
154
    /**
155
     * Set the value of path.
156
     *
157
     */
158
    public function setPath($path) : Cookie
159
    {
160
        $this->data['path'] = $path;
161
        return $this;
162
163
    }
164
165
    /**
166
     * Get the value of domain.
167
     */
168
    private function getDomain()
169
    {
170
        return $this->data['domain'];
171
    }
172
173
    /**
174
     * Set the value of domain.
175
     *
176
     */
177
    public function setDomain($domain)
178
    {
179
180
        if (!empty($domain)) {
181
            // Fix the domain to accept domains with and without 'www.'.
182
            if (strtolower(substr($domain, 0, 4)) == 'www.') {
183
                $this->data['domain'] = substr($domain, 4);
184
            }
185
186
            // Add the dot prefix to ensure compatibility with subdomains
187
            if (substr($domain, 0, 1) != '.') {
188
                $this->data['domain'] = '.' . $domain;
189
            }
190
            // Remove port information.
191
            $port = strpos($domain, ':');
192
            if (false !== $port) {
193
                $this->data['domain'] = substr($domain, 0, $port);
194
            }
195
        }
196
197
        return $this;
198
    }
199
200
    /**
201
     * Get the value of secure.
202
     */
203
    private function getSecure() : bool
204
    {
205
        return $this->data['secure'];
206
    }
207
208
    /**
209
     * Set the value of secure.
210
     *
211
     */
212
    public function setSecure($secure) : Cookie
213
    {
214
        $this->data['secure'] = $secure;
215
        return $this;
216
217
    }
218
219
    /**
220
     * Get the value of HTTPOnly.
221
     */
222
    private function getHTTPOnly() : bool
223
    {
224
        return $this->data['HTTPOnly'];
225
    }
226
227
    /**
228
     * Set the value of HTTPOnly.
229
     *
230
     */
231
    public function setHTTPOnly($HTTPOnly) : Cookie
232
    {
233
        $this->data['HTTPOnly'] = $HTTPOnly;
234
        return $this;
235
236
    }
237
238
    /**
239
     * @return mixed
240
     */
241
    private function getResponseCode()
242
    {
243
        return $this->responseCode;
244
    }
245
246
    /**
247
     * @param mixed $responseCode
248
     */
249
    public function setResponseCode($responseCode)
250
    {
251
        $this->responseCode = $responseCode;
252
        return $this;
253
    }
254
255
    public function getValue()
256
    {
257
        return $this->data['value'];
258
    }
259
260
    public function setValue($value) {
261
            $this->data['value'] = $value;
262
263
    }
264
265
    private function validate()
266
    {
267
        echo $this->getName();
268
        // Names must not be empty, but can be 0
269
        $name = $this->getName();
270
        if (empty($name) && !is_numeric($name)) {
271
            return 'The cookie name must not be empty';
272
        }
273
274
        // Check if any of the invalid characters are present in the cookie name
275
        if (preg_match(
276
            '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
277
            $name
278
        )) {
279
            return 'Cookie name must not contain invalid characters: ASCII '
280
                . 'Control characters (0-31;127), space, tab and the '
281
                . 'following characters: ()<>@,;:\"/?={}';
282
        }
283
284
        // Value must not be empty, but can be 0
285
        $value = $this->getValue();
286
        if (empty($value) && !is_numeric($value)) {
287
            return 'The cookie value must not be empty';
288
        }
289
290
        // Domains must not be empty, but can be 0
291
        // A "0" is not a valid internet domain, but may be used as server name
292
        // in a private network.
293
        $domain = $this->getDomain();
294
        if (empty($domain) && !is_numeric($domain)) {
295
            return 'The cookie domain must not be empty';
296
        }
297
298
        return true;
299
    }
300
}
301