Completed
Pull Request — master (#275)
by Alejandro
03:03 queued 43s
created

VisitService::locateVisit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 3
dl 0
loc 12
rs 10
c 0
b 0
f 0
ccs 7
cts 7
cp 1
crap 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