Passed
Pull Request — master (#293)
by Alejandro
04:32
created

GetVisitsAction::getDateQueryParam()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 2
nc 4
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Action\Visit;
5
6
use Psr\Http\Message\ResponseInterface as Response;
7
use Psr\Http\Message\ServerRequestInterface as Request;
8
use Psr\Log\LoggerInterface;
9
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
10
use Shlinkio\Shlink\Common\Paginator\Util\PaginatorUtilsTrait;
11
use Shlinkio\Shlink\Core\Model\VisitsParams;
12
use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface;
13
use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
14
use Shlinkio\Shlink\Rest\Util\RestUtils;
15
use Zend\Diactoros\Response\JsonResponse;
16
use function sprintf;
17
18
class GetVisitsAction extends AbstractRestAction
19
{
20
    use PaginatorUtilsTrait;
21
22
    protected const ROUTE_PATH = '/short-urls/{shortCode}/visits';
23
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
24
25
    /** @var VisitsTrackerInterface */
26
    private $visitsTracker;
27
28 3
    public function __construct(VisitsTrackerInterface $visitsTracker, LoggerInterface $logger = null)
29
    {
30 3
        parent::__construct($logger);
31 3
        $this->visitsTracker = $visitsTracker;
32
    }
33
34
    /**
35
     * @param Request $request
36
     * @return Response
37
     * @throws \InvalidArgumentException
38
     */
39 3
    public function handle(Request $request): Response
40
    {
41 3
        $shortCode = $request->getAttribute('shortCode');
42
43
        try {
44 3
            $visits = $this->visitsTracker->info($shortCode, VisitsParams::fromRawData($request->getQueryParams()));
45
46 2
            return new JsonResponse([
47 2
                'visits' => $this->serializePaginator($visits),
48
            ]);
49 1
        } catch (InvalidArgumentException $e) {
50 1
            $this->logger->warning('Provided nonexistent short code {e}', ['e' => $e]);
51 1
            return new JsonResponse([
52 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
53 1
                'message' => sprintf('Provided short code %s does not exist', $shortCode),
54 1
            ], self::STATUS_NOT_FOUND);
55
        }
56
    }
57
}
58