Completed
Pull Request — develop (#645)
by Alejandro
05:15
created

VisitsTracker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Service;
6
7
use Doctrine\ORM;
8
use Laminas\Paginator\Paginator;
9
use Psr\EventDispatcher\EventDispatcherInterface;
10
use Shlinkio\Shlink\Core\Entity\ShortUrl;
11
use Shlinkio\Shlink\Core\Entity\Visit;
12
use Shlinkio\Shlink\Core\EventDispatcher\ShortUrlVisited;
13
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
14
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
15
use Shlinkio\Shlink\Core\Model\Visitor;
16
use Shlinkio\Shlink\Core\Model\VisitsParams;
17
use Shlinkio\Shlink\Core\Paginator\Adapter\VisitsPaginatorAdapter;
18
use Shlinkio\Shlink\Core\Repository\ShortUrlRepositoryInterface;
19
use Shlinkio\Shlink\Core\Repository\VisitRepository;
20
21
class VisitsTracker implements VisitsTrackerInterface
22
{
23
    private ORM\EntityManagerInterface $em;
24
    private EventDispatcherInterface $eventDispatcher;
25
26 4
    public function __construct(ORM\EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher)
27
    {
28 4
        $this->em = $em;
29 4
        $this->eventDispatcher = $eventDispatcher;
30
    }
31
32
    /**
33
     * Tracks a new visit to provided short code from provided visitor
34
     */
35 2
    public function track(ShortUrl $shortUrl, Visitor $visitor): void
36
    {
37 2
        $visit = new Visit($shortUrl, $visitor);
38
39 2
        $this->em->persist($visit);
40 2
        $this->em->flush();
41
42 2
        $this->eventDispatcher->dispatch(new ShortUrlVisited($visit->getId()));
43
    }
44
45
    /**
46
     * Returns the visits on certain short code
47
     *
48
     * @return Visit[]|Paginator
49
     * @throws ShortUrlNotFoundException
50
     */
51 2
    public function info(ShortUrlIdentifier $identifier, VisitsParams $params): Paginator
52
    {
53
        /** @var ShortUrlRepositoryInterface $repo */
54 2
        $repo = $this->em->getRepository(ShortUrl::class);
55 2
        if (! $repo->shortCodeIsInUse($identifier->shortCode(), $identifier->domain())) {
56 1
            throw ShortUrlNotFoundException::fromNotFound($identifier);
57
        }
58
59
        /** @var VisitRepository $repo */
60 1
        $repo = $this->em->getRepository(Visit::class);
61 1
        $paginator = new Paginator(new VisitsPaginatorAdapter($repo, $identifier, $params));
62 1
        $paginator->setItemCountPerPage($params->getItemsPerPage())
63 1
                  ->setCurrentPageNumber($params->getPage());
64
65 1
        return $paginator;
66
    }
67
}
68