Completed
Pull Request — master (#359)
by Alejandro
05:37
created

VisitService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 18
dl 0
loc 42
rs 10
c 0
b 0
f 0
ccs 18
cts 18
cp 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A locateVisit() 0 12 2
A __construct() 0 3 1
A locateUnlocatedVisits() 0 17 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Service;
5
6
use Doctrine\ORM\EntityManagerInterface;
7
use Shlinkio\Shlink\Common\IpGeolocation\Model\Location;
8
use Shlinkio\Shlink\Core\Entity\Visit;
9
use Shlinkio\Shlink\Core\Entity\VisitLocation;
10
use Shlinkio\Shlink\Core\Exception\IpCannotBeLocatedException;
11
use Shlinkio\Shlink\Core\Repository\VisitRepository;
12
13
class VisitService implements VisitServiceInterface
14
{
15
    /** @var EntityManagerInterface */
16
    private $em;
17
18 2
    public function __construct(EntityManagerInterface $em)
19
    {
20 2
        $this->em = $em;
21
    }
22
23 2
    public function locateUnlocatedVisits(callable $geolocateVisit, ?callable $notifyVisitWithLocation = null): void
24
    {
25
        /** @var VisitRepository $repo */
26 2
        $repo = $this->em->getRepository(Visit::class);
27 2
        $results = $repo->findUnlocatedVisits();
28
29 2
        foreach ($results as [$visit]) {
30
            try {
31
                /** @var Location $location */
32 2
                $location = $geolocateVisit($visit);
33 1
            } catch (IpCannotBeLocatedException $e) {
34
                // Skip if the visit's IP could not be located
35 1
                continue;
36
            }
37
38 1
            $location = new VisitLocation($location);
39 1
            $this->locateVisit($visit, $location, $notifyVisitWithLocation);
40
        }
41
    }
42
43 1
    private function locateVisit(Visit $visit, VisitLocation $location, ?callable $notifyVisitWithLocation): void
44
    {
45 1
        $visit->locate($location);
46
47 1
        $this->em->persist($visit);
48 1
        $this->em->flush();
49
50 1
        if ($notifyVisitWithLocation !== null) {
51 1
            $notifyVisitWithLocation($location, $visit);
52
        }
53
54 1
        $this->em->clear();
55
    }
56
}
57