shlink/module/Core/src/Service/VisitsTracker.php

92 lines
2.7 KiB
PHP
Raw Normal View History

<?php
2017-10-12 11:13:20 +03:00
declare(strict_types=1);
2016-07-19 19:01:39 +03:00
namespace Shlinkio\Shlink\Core\Service;
use Doctrine\ORM;
use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Common\Util\DateRange;
2016-07-19 19:01:39 +03:00
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\Repository\VisitRepository;
class VisitsTracker implements VisitsTrackerInterface
{
/**
* @var ORM\EntityManagerInterface
*/
private $em;
public function __construct(ORM\EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* Tracks a new visit to provided short code, using an array of data to look up information
*
* @param string $shortCode
* @param ServerRequestInterface $request
* @throws ORM\ORMInvalidArgumentException
* @throws ORM\OptimisticLockException
*/
public function track($shortCode, ServerRequestInterface $request)
{
/** @var ShortUrl $shortUrl */
$shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
'shortCode' => $shortCode,
]);
$visit = new Visit();
$visit->setShortUrl($shortUrl)
->setUserAgent($request->getHeaderLine('User-Agent'))
->setReferer($request->getHeaderLine('Referer'))
->setRemoteAddr($this->findOutRemoteAddr($request));
2017-10-22 10:00:32 +03:00
/** @var ORM\EntityManager $em */
$em = $this->em;
$em->persist($visit);
$em->flush($visit);
}
/**
* @param ServerRequestInterface $request
2017-10-22 10:00:32 +03:00
* @return string|null
*/
2017-10-22 10:00:32 +03:00
private function findOutRemoteAddr(ServerRequestInterface $request)
{
$forwardedFor = $request->getHeaderLine('X-Forwarded-For');
if (empty($forwardedFor)) {
$serverParams = $request->getServerParams();
2017-10-22 10:00:32 +03:00
return $serverParams['REMOTE_ADDR'] ?? null;
}
$ips = explode(',', $forwardedFor);
2017-10-22 10:00:32 +03:00
return $ips[0] ?? null;
}
/**
* Returns the visits on certain short code
*
2017-12-27 18:23:54 +03:00
* @param string $shortCode
* @param DateRange $dateRange
* @return Visit[]
2017-10-22 10:00:32 +03:00
* @throws InvalidArgumentException
*/
2017-12-27 18:23:54 +03:00
public function info(string $shortCode, DateRange $dateRange = null): array
{
2017-12-27 18:23:54 +03:00
/** @var ShortUrl|null $shortUrl */
$shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
'shortCode' => $shortCode,
]);
2017-10-22 10:00:32 +03:00
if ($shortUrl === null) {
throw new InvalidArgumentException(sprintf('Short code "%s" not found', $shortCode));
}
/** @var VisitRepository $repo */
$repo = $this->em->getRepository(Visit::class);
return $repo->findVisitsByShortUrl($shortUrl, $dateRange);
}
}