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

CreateShortcodeAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 11
Ratio 100 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 4
dl 11
loc 11
rs 9.4285
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 1
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