Completed
Push — master ( f7ceef...6986d0 )
by Alejandro
16s
created

VisitsTracker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
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
use function sprintf;
14
15
class VisitsTracker implements VisitsTrackerInterface
16
{
17
    /**
18
     * @var ORM\EntityManagerInterface
19
     */
20
    private $em;
21
22 3
    public function __construct(ORM\EntityManagerInterface $em)
23
    {
24 3
        $this->em = $em;
25 3
    }
26
27
    /**
28
     * Tracks a new visit to provided short code from provided visitor
29
     */
30 2
    public function track(string $shortCode, Visitor $visitor): void
31
    {
32
        /** @var ShortUrl $shortUrl */
33 2
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
34 2
            'shortCode' => $shortCode,
35
        ]);
36
37 2
        $visit = new Visit($shortUrl, $visitor);
38
39
        /** @var ORM\EntityManager $em */
40 2
        $em = $this->em;
41 2
        $em->persist($visit);
42 2
        $em->flush($visit);
43 2
    }
44
45
    /**
46
     * Returns the visits on certain short code
47
     *
48
     * @param string $shortCode
49
     * @param DateRange $dateRange
50
     * @return Visit[]
51
     * @throws InvalidArgumentException
52
     */
53 1
    public function info(string $shortCode, DateRange $dateRange = null): array
54
    {
55
        /** @var ShortUrl|null $shortUrl */
56 1
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
57 1
            'shortCode' => $shortCode,
58
        ]);
59 1
        if ($shortUrl === null) {
60
            throw new InvalidArgumentException(sprintf('Short code "%s" not found', $shortCode));
61
        }
62
63
        /** @var VisitRepository $repo */
64 1
        $repo = $this->em->getRepository(Visit::class);
65 1
        return $repo->findVisitsByShortUrl($shortUrl, $dateRange);
66
    }
67
}
68