DistanceService::selectDistance()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 3
c 5
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 5
1
<?php
2
3
namespace SimpleCMS\Region\Services;
4
5
use Illuminate\Support\Facades\DB;
6
use Illuminate\Database\Query\Builder;
7
use SimpleCMS\Framework\Services\SimpleService;
8
9
class DistanceService
10
{
11
12
    /**
13
     * 获取距离RawString
14
     *
15
     * @author Dennis Lui <[email protected]>
16
     * @param  float  $lat
17
     * @param  float  $lng
18
     * @param  string $column
19
     * @return string
20
     */
21
    private function distanceRaw(float $lat, float $lng, string $column = 'location'): string
22
    {
23
        return "ST_Distance_Sphere($column,ST_GeomFromText('POINT($lng $lat)',4326))";
24
    }
25
26
    /**
27
     * 增加距离Select
28
     *
29
     * @author Dennis Lui <[email protected]>
30
     * @param  SimpleService $service
31
     * @param  float         $lat
32
     * @param  float         $lng
33
     * @param  string        $column
34
     * @return SimpleService
35
     */
36
    public function selectDistance(SimpleService $service, float $lat, float $lng, string $column = 'location', string $alias = 'distance'): SimpleService
37
    {
38
        $distanceRaw = $this->distanceRaw($lat, $lng, $column);
39
        $service->setSelect(DB::raw($distanceRaw . ' AS ' . $alias));
40
        return $service;
41
    }
42
43
    /**
44
     * 按距离查询
45
     *
46
     * @author Dennis Lui <[email protected]>
47
     * @param  SimpleService $service
48
     * @param  float         $lat
49
     * @param  float         $lng
50
     * @param  integer       $maxDistance
51
     * @param  string        $column
52
     * @return SimpleService
53
     */
54
    public function queryDistance(SimpleService $service, float $lat, float $lng, float $maxDistance = 50, string $column = 'location'): SimpleService
55
    {
56
        $this->selectDistance($service, $lat, $lng, $column);
57
        $distanceRaw = $this->distanceRaw($lat, $lng, $column);
58
        $service->setQuery(function (Builder $query) use ($distanceRaw, $maxDistance) {
59
            $query->whereRaw("$distanceRaw <= $maxDistance");
60
        });
61
        return $service;
62
    }
63
}