Completed
Push — master ( 1de050...162d05 )
by Alejandro
46:23 queued 09:21
created

VisitsTracker::info()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
ccs 6
cts 7
cp 0.8571
crap 2.0116
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Service;
5
6
use Doctrine\ORM;
7
use Shlinkio\Shlink\Common\Util\DateRange;
8
use Shlinkio\Shlink\Core\Entity\ShortUrl;
9
use Shlinkio\Shlink\Core\Entity\Visit;
10
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
11
use Shlinkio\Shlink\Core\Model\Visitor;
12
use Shlinkio\Shlink\Core\Repository\VisitRepository;
13
14
class VisitsTracker implements VisitsTrackerInterface
15
{
16
    /**
17
     * @var ORM\EntityManagerInterface
18
     */
19
    private $em;
20
21 3
    public function __construct(ORM\EntityManagerInterface $em)
22
    {
23 3
        $this->em = $em;
24 3
    }
25
26
    /**
27
     * Tracks a new visit to provided short code from provided visitor
28
     */
29 2
    public function track(string $shortCode, Visitor $visitor): void
30
    {
31
        /** @var ShortUrl $shortUrl */
32 2
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
33 2
            'shortCode' => $shortCode,
34
        ]);
35
36 2
        $visit = new Visit();
37 2
        $visit->setShortUrl($shortUrl)
38 2
              ->setUserAgent($visitor->getUserAgent())
39 2
              ->setReferer($visitor->getReferer())
40 2
              ->setRemoteAddr($visitor->getRemoteAddress());
41
42
        /** @var ORM\EntityManager $em */
43 2
        $em = $this->em;
44 2
        $em->persist($visit);
45 2
        $em->flush($visit);
46 2
    }
47
48
    /**
49
     * Returns the visits on certain short code
50
     *
51
     * @param string $shortCode
52
     * @param DateRange $dateRange
53
     * @return Visit[]
54
     * @throws InvalidArgumentException
55
     */
56 1
    public function info(string $shortCode, DateRange $dateRange = null): array
57
    {
58
        /** @var ShortUrl|null $shortUrl */
59 1
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
60 1
            'shortCode' => $shortCode,
61
        ]);
62 1
        if ($shortUrl === null) {
63
            throw new InvalidArgumentException(sprintf('Short code "%s" not found', $shortCode));
64
        }
65
66
        /** @var VisitRepository $repo */
67 1
        $repo = $this->em->getRepository(Visit::class);
68 1
        return $repo->findVisitsByShortUrl($shortUrl, $dateRange);
69
    }
70
}
71