ResolveShortUrlAction.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
  4. use InvalidArgumentException;
  5. use Laminas\Diactoros\Response\JsonResponse;
  6. use Psr\Http\Message\ResponseInterface as Response;
  7. use Psr\Http\Message\ServerRequestInterface as Request;
  8. use Psr\Log\LoggerInterface;
  9. use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
  10. use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
  11. use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
  12. class ResolveShortUrlAction extends AbstractRestAction
  13. {
  14. protected const ROUTE_PATH = '/short-urls/{shortCode}';
  15. protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
  16. private UrlShortenerInterface $urlShortener;
  17. private array $domainConfig;
  18. public function __construct(
  19. UrlShortenerInterface $urlShortener,
  20. array $domainConfig,
  21. ?LoggerInterface $logger = null
  22. ) {
  23. parent::__construct($logger);
  24. $this->urlShortener = $urlShortener;
  25. $this->domainConfig = $domainConfig;
  26. }
  27. /**
  28. * @throws InvalidArgumentException
  29. */
  30. public function handle(Request $request): Response
  31. {
  32. $shortCode = $request->getAttribute('shortCode');
  33. $domain = $request->getQueryParams()['domain'] ?? null;
  34. $transformer = new ShortUrlDataTransformer($this->domainConfig);
  35. $url = $this->urlShortener->shortCodeToUrl($shortCode, $domain);
  36. return new JsonResponse($transformer->transform($url));
  37. }
  38. }