Completed
Push — master ( 136319...17fcd6 )
by Alejandro
13s queued 11s
created

VisitService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A locateVisits() 0 16 3
A locateVisit() 0 12 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Service;
5
6
use Doctrine\ORM\EntityManagerInterface;
7
use Shlinkio\Shlink\Core\Entity\Visit;
8
use Shlinkio\Shlink\Core\Entity\VisitLocation;
9
use Shlinkio\Shlink\Core\Exception\IpCannotBeLocatedException;
10
use Shlinkio\Shlink\Core\Repository\VisitRepository;
11
12
class VisitService implements VisitServiceInterface
13
{
14
    /**
15
     * @var EntityManagerInterface
16
     */
17
    private $em;
18
19 2
    public function __construct(EntityManagerInterface $em)
20
    {
21 2
        $this->em = $em;
22
    }
23
24 2
    public function locateVisits(callable $getGeolocationData, ?callable $locatedVisit = null): void
25
    {
26
        /** @var VisitRepository $repo */
27 2
        $repo = $this->em->getRepository(Visit::class);
28 2
        $results = $repo->findUnlocatedVisits();
29
30 2
        foreach ($results as [$visit]) {
31
            try {
32 2
                $locationData = $getGeolocationData($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($locationData);
39 1
            $this->locateVisit($visit, $location, $locatedVisit);
40
        }
41
    }
42
43 1
    private function locateVisit(Visit $visit, VisitLocation $location, ?callable $locatedVisit): void
44
    {
45 1
        $visit->locate($location);
46
47 1
        $this->em->persist($visit);
48 1
        $this->em->flush();
49
50 1
        if ($locatedVisit !== null) {
51 1
            $locatedVisit($location, $visit);
52
        }
53
54 1
        $this->em->clear();
55
    }
56
}
57