Passed
Pull Request — master (#359)
by Alejandro
05:46
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\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