Completed
Pull Request — master (#148)
by Alejandro
04:16
created

CreateShortCodeAction::getOptionalDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 2
rs 10
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 5
    protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData
24
    {
25 5
        $postData = (array) $request->getParsedBody();
26 5
        if (! isset($postData['longUrl'])) {
27 1
            throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
28
        }
29
30 4
        return new CreateShortCodeData(
31 4
            new Uri($postData['longUrl']),
32 4
            (array) ($postData['tags'] ?? []),
33 4
            ShortUrlMeta::createFromParams(
34 4
                $this->getOptionalDate($postData, 'validSince'),
35 4
                $this->getOptionalDate($postData, 'validUntil'),
36 4
                $postData['customSlug'] ?? null,
37 4
                isset($postData['maxVisits']) ? (int) $postData['maxVisits'] : null
38
            )
39
        );
40
    }
41
42 4
    private function getOptionalDate(array $postData, string $fieldName)
43
    {
44 4
        return isset($postData[$fieldName]) ? new \DateTime($postData[$fieldName]) : null;
45
    }
46
}
47