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

CreateShortCodeAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 35
rs 10
wmc 5
lcom 1
cbo 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A buildUrlToShortCodeData() 0 18 3
A getOptionalDate() 0 4 2
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