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

CreateShortCodeAction::buildUrlToShortCodeData()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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