AbstractCreateShortUrlAction.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
  4. use Laminas\Diactoros\Response\JsonResponse;
  5. use Psr\Http\Message\ResponseInterface as Response;
  6. use Psr\Http\Message\ServerRequestInterface as Request;
  7. use Psr\Log\LoggerInterface;
  8. use Shlinkio\Shlink\Core\Exception\ValidationException;
  9. use Shlinkio\Shlink\Core\Model\CreateShortUrlData;
  10. use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
  11. use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
  12. use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
  13. abstract class AbstractCreateShortUrlAction extends AbstractRestAction
  14. {
  15. private UrlShortenerInterface $urlShortener;
  16. private array $domainConfig;
  17. public function __construct(
  18. UrlShortenerInterface $urlShortener,
  19. array $domainConfig,
  20. ?LoggerInterface $logger = null
  21. ) {
  22. parent::__construct($logger);
  23. $this->urlShortener = $urlShortener;
  24. $this->domainConfig = $domainConfig;
  25. }
  26. public function handle(Request $request): Response
  27. {
  28. $shortUrlData = $this->buildShortUrlData($request);
  29. $longUrl = $shortUrlData->getLongUrl();
  30. $tags = $shortUrlData->getTags();
  31. $shortUrlMeta = $shortUrlData->getMeta();
  32. $shortUrl = $this->urlShortener->urlToShortCode($longUrl, $tags, $shortUrlMeta);
  33. $transformer = new ShortUrlDataTransformer($this->domainConfig);
  34. return new JsonResponse($transformer->transform($shortUrl));
  35. }
  36. /**
  37. * @throws ValidationException
  38. */
  39. abstract protected function buildShortUrlData(Request $request): CreateShortUrlData;
  40. }