1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Shlinkio\Shlink\Core\Service; |
5
|
|
|
|
6
|
|
|
use Doctrine\ORM; |
7
|
|
|
use Shlinkio\Shlink\Core\Entity\ShortUrl; |
8
|
|
|
use Shlinkio\Shlink\Core\Entity\Visit; |
9
|
|
|
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; |
10
|
|
|
use Shlinkio\Shlink\Core\Model\Visitor; |
11
|
|
|
use Shlinkio\Shlink\Core\Model\VisitsParams; |
12
|
|
|
use Shlinkio\Shlink\Core\Paginator\Adapter\VisitsPaginatorAdapter; |
13
|
|
|
use Shlinkio\Shlink\Core\Repository\VisitRepository; |
14
|
|
|
use Zend\Paginator\Paginator; |
15
|
|
|
use function sprintf; |
16
|
|
|
|
17
|
|
|
class VisitsTracker implements VisitsTrackerInterface |
18
|
|
|
{ |
19
|
|
|
/** @var ORM\EntityManagerInterface */ |
20
|
|
|
private $em; |
21
|
|
|
|
22
|
3 |
|
public function __construct(ORM\EntityManagerInterface $em) |
23
|
|
|
{ |
24
|
3 |
|
$this->em = $em; |
25
|
|
|
} |
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
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Returns the visits on certain short code |
47
|
|
|
* |
48
|
|
|
* @return Visit[]|Paginator |
49
|
|
|
* @throws InvalidArgumentException |
50
|
|
|
*/ |
51
|
1 |
|
public function info(string $shortCode, VisitsParams $params): Paginator |
52
|
|
|
{ |
53
|
|
|
/** @var ORM\EntityRepository $repo */ |
54
|
1 |
|
$repo = $this->em->getRepository(ShortUrl::class); |
55
|
1 |
|
if ($repo->count(['shortCode' => $shortCode]) < 1) { |
56
|
|
|
throw new InvalidArgumentException(sprintf('Short code "%s" not found', $shortCode)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** @var VisitRepository $repo */ |
60
|
1 |
|
$repo = $this->em->getRepository(Visit::class); |
61
|
1 |
|
$paginator = new Paginator(new VisitsPaginatorAdapter($repo, $shortCode, $params)); |
62
|
1 |
|
$paginator->setItemCountPerPage($params->hasItemsPerPage() ? $params->getItemsPerPage() : -1) |
63
|
1 |
|
->setCurrentPageNumber($params->getPage()); |
64
|
|
|
|
65
|
1 |
|
return $paginator; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|