|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace HttpSoft\Tests\Basis\Handler; |
| 6 | + |
| 7 | +use HttpSoft\Basis\Handler\NotFoundJsonHandler; |
| 8 | +use HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface; |
| 9 | +use HttpSoft\Message\ServerRequestFactory; |
| 10 | +use HttpSoft\Tests\Basis\TestAsset\TraitMethodsWrapper; |
| 11 | +use PHPUnit\Framework\TestCase; |
| 12 | +use Psr\Http\Message\ServerRequestInterface; |
| 13 | + |
| 14 | +class NotFoundJsonHandlerTest extends TestCase |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @var ServerRequestInterface |
| 18 | + */ |
| 19 | + private ServerRequestInterface $request; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var TraitMethodsWrapper |
| 23 | + */ |
| 24 | + private TraitMethodsWrapper $traits; |
| 25 | + |
| 26 | + /** |
| 27 | + * @var int |
| 28 | + */ |
| 29 | + private int $statusCode = ErrorResponseGeneratorInterface::STATUS_NOT_FOUND; |
| 30 | + |
| 31 | + public function setUp(): void |
| 32 | + { |
| 33 | + $this->request = (new ServerRequestFactory())->createServerRequest( |
| 34 | + 'POST', |
| 35 | + 'http://example.com', |
| 36 | + ['name' => 'value'] |
| 37 | + ); |
| 38 | + $this->traits = new TraitMethodsWrapper(); |
| 39 | + } |
| 40 | + |
| 41 | + public function testHandleWithoutDebugMode(): void |
| 42 | + { |
| 43 | + $handler = new NotFoundJsonHandler(false); |
| 44 | + $response = $handler->handle($this->request); |
| 45 | + |
| 46 | + $expectedContent = $this->encode([ |
| 47 | + 'name' => 'Error', |
| 48 | + 'code' => $this->statusCode, |
| 49 | + 'message' => ErrorResponseGeneratorInterface::ERROR_PHRASES[$this->statusCode], |
| 50 | + ]); |
| 51 | + $this->assertSame($expectedContent, (string) $response->getBody()); |
| 52 | + } |
| 53 | + |
| 54 | + public function testHandleWithDebugMode(): void |
| 55 | + { |
| 56 | + $handler = new NotFoundJsonHandler(true); |
| 57 | + $response = $handler->handle($this->request); |
| 58 | + |
| 59 | + $expectedContent = $this->encode([ |
| 60 | + 'name' => 'Error', |
| 61 | + 'code' => $this->statusCode, |
| 62 | + 'message' => ErrorResponseGeneratorInterface::ERROR_PHRASES[$this->statusCode], |
| 63 | + 'request' => $this->traits->extractRequestData($this->request), |
| 64 | + ]); |
| 65 | + $this->assertSame($expectedContent, (string) $response->getBody()); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @param mixed $data |
| 70 | + * @return string |
| 71 | + */ |
| 72 | + private function encode($data): string |
| 73 | + { |
| 74 | + return json_encode($this->traits->prepareJsonData($data), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
| 75 | + } |
| 76 | +} |
0 commit comments