SingleStepCreateShortUrlAction.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
  4. use Laminas\Diactoros\Uri;
  5. use Psr\Http\Message\ServerRequestInterface as Request;
  6. use Psr\Log\LoggerInterface;
  7. use Shlinkio\Shlink\Core\Exception\ValidationException;
  8. use Shlinkio\Shlink\Core\Model\CreateShortUrlData;
  9. use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
  10. use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
  11. class SingleStepCreateShortUrlAction extends AbstractCreateShortUrlAction
  12. {
  13. protected const ROUTE_PATH = '/short-urls/shorten';
  14. protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
  15. private ApiKeyServiceInterface $apiKeyService;
  16. public function __construct(
  17. UrlShortenerInterface $urlShortener,
  18. ApiKeyServiceInterface $apiKeyService,
  19. array $domainConfig,
  20. ?LoggerInterface $logger = null
  21. ) {
  22. parent::__construct($urlShortener, $domainConfig, $logger);
  23. $this->apiKeyService = $apiKeyService;
  24. }
  25. /**
  26. * @throws ValidationException
  27. */
  28. protected function buildShortUrlData(Request $request): CreateShortUrlData
  29. {
  30. $query = $request->getQueryParams();
  31. if (! $this->apiKeyService->check($query['apiKey'] ?? '')) {
  32. throw ValidationException::fromArray([
  33. 'apiKey' => 'No API key was provided or it is not valid',
  34. ]);
  35. }
  36. if (! isset($query['longUrl'])) {
  37. throw ValidationException::fromArray([
  38. 'longUrl' => 'A URL was not provided',
  39. ]);
  40. }
  41. return new CreateShortUrlData(new Uri($query['longUrl']));
  42. }
  43. }