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

CreateShortcodeAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

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