middleware = new CreateShortUrlContentNegotiationMiddleware(); $this->requestHandler = $this->createMock(RequestHandlerInterface::class); } /** @test */ public function whenNoJsonResponseIsReturnedNoFurtherOperationsArePerformed(): void { $expectedResp = new Response(); $this->requestHandler->method('handle')->with($this->isInstanceOf(ServerRequestInterface::class))->willReturn( $expectedResp, ); $resp = $this->middleware->process(new ServerRequest(), $this->requestHandler); self::assertSame($expectedResp, $resp); } /** * @test * @dataProvider provideData * @param array $query */ public function properResponseIsReturned(?string $accept, array $query, string $expectedContentType): void { $request = (new ServerRequest())->withQueryParams($query); if ($accept !== null) { $request = $request->withHeader('Accept', $accept); } $this->requestHandler->expects($this->once())->method('handle')->with( $this->isInstanceOf(ServerRequestInterface::class), )->willReturn(new JsonResponse(['shortUrl' => 'http://s.test/foo'])); $response = $this->middleware->process($request, $this->requestHandler); self::assertEquals($expectedContentType, $response->getHeaderLine('Content-type')); } public function provideData(): iterable { yield [null, [], 'application/json']; yield [null, ['format' => 'json'], 'application/json']; yield [null, ['format' => 'invalid'], 'application/json']; yield [null, ['format' => 'txt'], 'text/plain']; yield ['application/json', [], 'application/json']; yield ['application/xml', [], 'application/json']; yield ['text/plain', [], 'text/plain']; yield ['application/json', ['format' => 'txt'], 'text/plain']; } /** * @test * @dataProvider provideTextBodies * @param array $json */ public function properBodyIsReturnedInPlainTextResponses(array $json, string $expectedBody): void { $request = (new ServerRequest())->withQueryParams(['format' => 'txt']); $this->requestHandler->expects($this->once())->method('handle')->with( $this->isInstanceOf(ServerRequestInterface::class), )->willReturn(new JsonResponse($json)); $response = $this->middleware->process($request, $this->requestHandler); self::assertEquals($expectedBody, (string) $response->getBody()); } public function provideTextBodies(): iterable { yield 'shortUrl key' => [['shortUrl' => 'foobar'], 'foobar']; yield 'error key' => [['error' => 'FOO_BAR'], 'FOO_BAR']; yield 'no shortUrl or error keys' => [[], '']; } }