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( |
27
|
|
|
'/test', |
28
|
|
|
static function () use ($dataResponse) { |
29
|
|
|
return $dataResponse; |
30
|
|
|
}, |
31
|
|
|
$this->getContainer([FormatDataResponse::class => new FormatDataResponse(new JsonDataResponseFormatter())]) |
32
|
|
|
)->addMiddleware(FormatDataResponse::class); |
33
|
|
|
$result = $route->process($request, $this->getRequestHandler()); |
34
|
|
|
$result->getBody()->rewind(); |
35
|
|
|
|
36
|
|
|
$this->assertSame('{"test":"test"}', $result->getBody()->getContents()); |
37
|
|
|
$this->assertSame(['application/json'], $result->getHeader('Content-Type')); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function getContainer(array $instances): ContainerInterface |
41
|
|
|
{ |
42
|
|
|
return new class($instances) implements ContainerInterface { |
43
|
|
|
private array $instances; |
44
|
|
|
|
45
|
|
|
public function __construct(array $instances) |
46
|
|
|
{ |
47
|
|
|
$this->instances = $instances; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function get($id) |
51
|
|
|
{ |
52
|
|
|
return $this->instances[$id]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function has($id) |
56
|
|
|
{ |
57
|
|
|
return isset($this->instances[$id]); |
58
|
|
|
} |
59
|
|
|
}; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function getRequestHandler(): RequestHandlerInterface |
63
|
|
|
{ |
64
|
|
|
return new class() implements RequestHandlerInterface { |
65
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
66
|
|
|
{ |
67
|
|
|
return new Response(Status::NOT_FOUND); |
68
|
|
|
} |
69
|
|
|
}; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|