shlink/module/Rest/src/Action/ResolveUrlMiddleware.php

66 lines
2.1 KiB
PHP
Raw Normal View History

2016-06-12 22:31:28 +03:00
<?php
2016-07-19 18:07:59 +03:00
namespace Shlinkio\Shlink\Rest\Action;
2016-06-12 22:31:28 +03:00
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
2016-07-19 19:01:39 +03:00
use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException;
use Shlinkio\Shlink\Core\Service\UrlShortener;
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
2016-07-19 18:07:59 +03:00
use Shlinkio\Shlink\Rest\Util\RestUtils;
2016-06-12 22:31:28 +03:00
use Zend\Diactoros\Response\JsonResponse;
2016-07-05 20:19:23 +03:00
class ResolveUrlMiddleware extends AbstractRestMiddleware
2016-06-12 22:31:28 +03:00
{
/**
* @var UrlShortenerInterface
*/
private $urlShortener;
/**
* ResolveUrlMiddleware constructor.
* @param UrlShortenerInterface|UrlShortener $urlShortener
*
* @Inject({UrlShortener::class})
*/
public function __construct(UrlShortenerInterface $urlShortener)
{
$this->urlShortener = $urlShortener;
}
/**
* @param Request $request
* @param Response $response
2016-07-05 20:19:23 +03:00
* @param callable|null $out
2016-06-12 22:31:28 +03:00
* @return null|Response
*/
2016-07-05 20:19:23 +03:00
public function dispatch(Request $request, Response $response, callable $out = null)
2016-06-12 22:31:28 +03:00
{
$shortCode = $request->getAttribute('shortCode');
try {
$longUrl = $this->urlShortener->shortCodeToUrl($shortCode);
if (! isset($longUrl)) {
return new JsonResponse([
'error' => RestUtils::INVALID_ARGUMENT_ERROR,
'message' => sprintf('No URL found for shortcode "%s"', $shortCode),
], 400);
}
return new JsonResponse([
'longUrl' => $longUrl,
]);
} catch (InvalidShortCodeException $e) {
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => sprintf('Provided short code "%s" has an invalid format', $shortCode),
], 400);
} catch (\Exception $e) {
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => 'Unexpected error occured',
], 500);
}
}
}