Completed
Pull Request — master (#148)
by Alejandro
02:40
created

CreateShortCodeAction::getOptionalDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Action\ShortCode;
5
6
use Psr\Http\Message\ServerRequestInterface as Request;
7
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
8
use Shlinkio\Shlink\Core\Model\CreateShortCodeData;
9
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
10
use Zend\Diactoros\Uri;
11
12
class CreateShortCodeAction extends AbstractCreateShortCodeAction
13
{
14
    protected const ROUTE_PATH = '/short-codes';
15
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_POST];
16
17
    /**
18
     * @param Request $request
19
     * @return CreateShortCodeData
20
     * @throws InvalidArgumentException
21
     * @throws \InvalidArgumentException
22
     */
23
    protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData
24
    {
25
        $postData = (array) $request->getParsedBody();
26
        if (! isset($postData['longUrl'])) {
27
            throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
28
        }
29
30
        return new CreateShortCodeData(
31
            new Uri($postData['longUrl']),
32
            (array) ($postData['tags'] ?? []),
33
            ShortUrlMeta::createFromParams(
34
                $this->getOptionalDate($postData, 'validSince'),
35
                $this->getOptionalDate($postData, 'validUntil'),
36
                $postData['customSlug'] ?? null,
37
                isset($postData['maxVisits']) ? (int) $postData['maxVisits'] : null
38
            )
39
        );
40
    }
41
42
    private function getOptionalDate(array $postData, string $fieldName)
43
    {
44
        return isset($postData[$fieldName]) ? new \DateTime($postData[$fieldName]) : null;
45
    }
46
}
47