1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yiisoft\Yii\Web\Tests\Middleware; |
4
|
|
|
|
5
|
|
|
use Nyholm\Psr7\Factory\Psr17Factory; |
6
|
|
|
use Nyholm\Psr7\Response; |
7
|
|
|
use Nyholm\Psr7\ServerRequest; |
8
|
|
|
use PHPUnit\Framework\TestCase; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
12
|
|
|
use Yiisoft\Http\Method; |
13
|
|
|
use Yiisoft\Yii\Web\Middleware\HttpCache; |
14
|
|
|
|
15
|
|
|
class HttpCacheTest extends TestCase |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @test |
19
|
|
|
*/ |
20
|
|
|
public function modifiedResult(): void |
21
|
|
|
{ |
22
|
|
|
$time = \time(); |
23
|
|
|
$middleware = $this->createMiddlewareWithLastModified($time + 1); |
24
|
|
|
$headers = [ |
25
|
|
|
'If-Modified-Since' => gmdate('D, d M Y H:i:s', $time) . 'GMT', |
26
|
|
|
]; |
27
|
|
|
$response = $middleware->process($this->createServerRequest(Method::GET, $headers), $this->createRequestHandler()); |
28
|
|
|
$this->assertEquals(200, $response->getStatusCode()); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @test |
33
|
|
|
*/ |
34
|
|
|
public function notModifiedResult(): void |
35
|
|
|
{ |
36
|
|
|
$time = \time(); |
37
|
|
|
$middleware = $this->createMiddlewareWithLastModified($time - 1); |
38
|
|
|
$headers = [ |
39
|
|
|
'If-Modified-Since' => gmdate('D, d M Y H:i:s', $time) . 'GMT', |
40
|
|
|
]; |
41
|
|
|
$response = $middleware->process($this->createServerRequest(Method::GET, $headers), $this->createRequestHandler()); |
42
|
|
|
$this->assertEquals(304, $response->getStatusCode()); |
43
|
|
|
$this->assertEmpty((string)$response->getBody()); |
44
|
|
|
$this->assertEquals(gmdate('D, d M Y H:i:s', $time - 1) . ' GMT', $response->getHeaderLine('Last-Modified')); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function createMiddlewareWithLastModified(int $lastModified): HttpCache |
48
|
|
|
{ |
49
|
|
|
$middleware = new HttpCache(new Psr17Factory()); |
50
|
|
|
$middleware->setLastModified(static function (ServerRequestInterface $request, $params) use ($lastModified) { |
|
|
|
|
51
|
|
|
return $lastModified; |
52
|
|
|
}); |
53
|
|
|
return $middleware; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function createRequestHandler(): RequestHandlerInterface |
57
|
|
|
{ |
58
|
|
|
return new class implements RequestHandlerInterface { |
59
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
60
|
|
|
{ |
61
|
|
|
return new Response(200); |
62
|
|
|
} |
63
|
|
|
}; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function createServerRequest(string $method = Method::GET, $headers = []): ServerRequestInterface |
67
|
|
|
{ |
68
|
|
|
return new ServerRequest($method, '/', $headers); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.