Completed
Push — master ( 5c5dde...08bd4f )
by Alejandro
17s queued 10s
created

VisitService::locateUnlocatedVisits()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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