-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Context.php
83 lines (63 loc) · 1.72 KB
/
Context.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
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Http;
/**
* HTTP-specific tasks.
*/
class Context
{
public function __construct(
private readonly IRequest $request,
private readonly IResponse $response,
) {
}
/**
* Attempts to cache the sent entity by its last modification date.
*/
public function isModified(string|int|\DateTimeInterface|null $lastModified = null, ?string $etag = null): bool
{
if ($lastModified) {
$this->response->setHeader('Last-Modified', Helpers::formatDate($lastModified));
}
if ($etag) {
$this->response->setHeader('ETag', '"' . addslashes($etag) . '"');
}
$ifNoneMatch = $this->request->getHeader('If-None-Match');
if ($ifNoneMatch === '*') {
$match = true; // match, check if-modified-since
} elseif ($ifNoneMatch !== null) {
$etag = $this->response->getHeader('ETag');
if ($etag === null || !str_contains(' ' . strtr($ifNoneMatch, ",\t", ' '), ' ' . $etag)) {
return true;
} else {
$match = true; // match, check if-modified-since
}
}
$ifModifiedSince = $this->request->getHeader('If-Modified-Since');
if ($ifModifiedSince !== null) {
$lastModified = $this->response->getHeader('Last-Modified');
if ($lastModified !== null && strtotime($lastModified) <= strtotime($ifModifiedSince)) {
$match = true;
} else {
return true;
}
}
if (empty($match)) {
return true;
}
$this->response->setCode(IResponse::S304_NotModified);
return false;
}
public function getRequest(): IRequest
{
return $this->request;
}
public function getResponse(): IResponse
{
return $this->response;
}
}