Files
shlink/module/Rest/src/Action/ShortUrl/CreateShortUrlAction.php

48 lines
1.6 KiB
PHP
Raw Normal View History

<?php
2017-10-12 10:13:20 +02:00
declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Core\Model\CreateShortUrlData;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Rest\Action\ShortUrl\AbstractCreateShortUrlAction;
use Zend\Diactoros\Uri;
class CreateShortUrlAction extends AbstractCreateShortUrlAction
{
protected const ROUTE_PATH = '/short-urls';
protected const ROUTE_ALLOWED_METHODS = [self::METHOD_POST];
/**
* @param Request $request
* @return CreateShortUrlData
* @throws InvalidArgumentException
2017-07-07 13:12:45 +02:00
* @throws \InvalidArgumentException
*/
protected function buildShortUrlData(Request $request): CreateShortUrlData
{
2017-12-27 16:23:54 +01:00
$postData = (array) $request->getParsedBody();
if (! isset($postData['longUrl'])) {
throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
}
return new CreateShortUrlData(
new Uri($postData['longUrl']),
(array) ($postData['tags'] ?? []),
ShortUrlMeta::createFromParams(
$this->getOptionalDate($postData, 'validSince'),
$this->getOptionalDate($postData, 'validUntil'),
$postData['customSlug'] ?? null,
isset($postData['maxVisits']) ? (int) $postData['maxVisits'] : null
)
);
}
private function getOptionalDate(array $postData, string $fieldName)
{
return isset($postData[$fieldName]) ? new \DateTime($postData[$fieldName]) : null;
}
}