|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yiisoft\Yii\Web\Tests\Data\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\Container\ContainerInterface; |
|
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
11
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
12
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
13
|
|
|
use Yiisoft\Http\Status; |
|
14
|
|
|
use Yiisoft\Router\Route; |
|
15
|
|
|
use Yiisoft\Yii\Web\Data\Formatter\JsonDataResponseFormatter; |
|
16
|
|
|
use Yiisoft\Yii\Web\Data\Middleware\FormatDataResponse; |
|
17
|
|
|
use Yiisoft\Yii\Web\Data\DataResponse; |
|
18
|
|
|
|
|
19
|
|
|
class FormatDataResponseTest extends TestCase |
|
20
|
|
|
{ |
|
21
|
|
|
public function testFormatter(): void |
|
22
|
|
|
{ |
|
23
|
|
|
$request = new ServerRequest('GET', '/test'); |
|
24
|
|
|
$factory = new Psr17Factory(); |
|
25
|
|
|
$dataResponse = new DataResponse(['test' => 'test'], 200, '', $factory); |
|
26
|
|
|
$route = Route::get('/test', static function () use ($dataResponse) { |
|
27
|
|
|
return $dataResponse; |
|
28
|
|
|
}, $this->getContainer())->addMiddleware(FormatDataResponse::class); |
|
29
|
|
|
$result = $route->process($request, $this->getRequestHandler()); |
|
30
|
|
|
$result->getBody()->rewind(); |
|
31
|
|
|
|
|
32
|
|
|
$this->assertSame('{"test":"test"}', $result->getBody()->getContents()); |
|
33
|
|
|
$this->assertSame(['application/json'], $result->getHeader('Content-Type')); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
private function getContainer(): ContainerInterface |
|
37
|
|
|
{ |
|
38
|
|
|
return new class() implements ContainerInterface { |
|
39
|
|
|
private array $instances; |
|
40
|
|
|
|
|
41
|
|
|
public function __construct() |
|
42
|
|
|
{ |
|
43
|
|
|
$this->instances = [ |
|
44
|
|
|
FormatDataResponse::class => new FormatDataResponse(new JsonDataResponseFormatter()) |
|
45
|
|
|
]; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function get($id) |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->instances[$id]; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function has($id) |
|
54
|
|
|
{ |
|
55
|
|
|
return isset($this->instances[$id]); |
|
56
|
|
|
} |
|
57
|
|
|
}; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function getRequestHandler(): RequestHandlerInterface |
|
61
|
|
|
{ |
|
62
|
|
|
return new class() implements RequestHandlerInterface { |
|
63
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
64
|
|
|
{ |
|
65
|
|
|
return new Response(Status::NOT_FOUND); |
|
66
|
|
|
} |
|
67
|
|
|
}; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|