From 59f10619ba4a64e1a43720d365839f6d714d436d Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Thu, 3 May 2018 18:26:31 +0200 Subject: [PATCH] Created middleware used with short codes creation actions to handle content negotiation --- module/Rest/config/dependencies.config.php | 1 + module/Rest/config/routes.config.php | 10 +++- .../AbstractCreateShortCodeAction.php | 1 - ...eShortCodeContentNegotiationMiddleware.php | 47 +++++++++++++++++++ 4 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 module/Rest/src/Middleware/ShortCode/CreateShortCodeContentNegotiationMiddleware.php diff --git a/module/Rest/config/dependencies.config.php b/module/Rest/config/dependencies.config.php index 72198c3f..304e667d 100644 --- a/module/Rest/config/dependencies.config.php +++ b/module/Rest/config/dependencies.config.php @@ -36,6 +36,7 @@ return [ Middleware\CrossDomainMiddleware::class => InvokableFactory::class, Middleware\PathVersionMiddleware::class => InvokableFactory::class, Middleware\CheckAuthenticationMiddleware::class => ConfigAbstractFactory::class, + Middleware\ShortCode\CreateShortCodeContentNegotiationMiddleware::class => InvokableFactory::class, ], ], diff --git a/module/Rest/config/routes.config.php b/module/Rest/config/routes.config.php index 24d70cdd..0f453e26 100644 --- a/module/Rest/config/routes.config.php +++ b/module/Rest/config/routes.config.php @@ -1,6 +1,8 @@ withScheme($this->domainConfig['schema']) ->withHost($this->domainConfig['hostname']); - // TODO Make response to be generated based on Accept header return new JsonResponse([ 'longUrl' => (string) $longUrl, 'shortUrl' => (string) $shortUrl, diff --git a/module/Rest/src/Middleware/ShortCode/CreateShortCodeContentNegotiationMiddleware.php b/module/Rest/src/Middleware/ShortCode/CreateShortCodeContentNegotiationMiddleware.php new file mode 100644 index 00000000..41ce8813 --- /dev/null +++ b/module/Rest/src/Middleware/ShortCode/CreateShortCodeContentNegotiationMiddleware.php @@ -0,0 +1,47 @@ +handle($request); + $acceptedType = $this->determineAcceptedType($request); + if ($acceptedType === self::JSON) { + return $response; + } + + // If requested, return a plain text response containing the short URL only + $resp = (new Response())->withHeader('Content-Type', 'text/plain'); + $body = $resp->getBody(); + $body->write($response->getPayload()['shortUrl'] ?? ''); + $body->rewind(); + return $resp; + } + + private function determineAcceptedType(ServerRequestInterface $request): string + { + $accepts = \explode(',', $request->getHeaderLine('Accept')); + $accept = \strtolower(\array_shift($accepts)); + return \strpos($accept, 'text/plain') !== false ? self::PLAIN_TEXT : self::JSON; + } +}