Completed
Push — master ( bd8a0b...d8e69c )
by Tommy
01:03
created

HasGeoAbilities::databaseDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Leitom\Geo;
4
5
use Illuminate\Support\Arr;
6
use Leitom\Geo\Facades\Geo;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Leitom\Geo\Geo.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Illuminate\Support\Facades\DB;
8
use Leitom\Geo\Events\ModelsRemoved;
9
use Leitom\Geo\Events\ModelsImported;
10
use Illuminate\Support\Collection as BaseCollection;
11
12
trait HasGeoAbilities
13
{
14
    public $geoEnabled = true;
15
16
    public static function bootHasGeoAbilities()
17
    {
18
        static::addGlobalScope(new GeoScope);
19
20
        static::observe(new ModelObserver);
21
22
        (new static)->registerGeoMacros();
23
    }
24
25
    public function registerGeoMacros()
26
    {
27
        $self = $this;
28
29
        BaseCollection::macro('addGeo', function () use ($self) {
30
            $self->addGeo($this);
31
        });
32
33
        BaseCollection::macro('removeGeo', function () use ($self) {
34
            $self->removeGeo($this);
35
        });
36
    }
37
38
    public function addGeo($models)
39
    {
40
        if ($models->isEmpty()) {
41
            return;
42
        }
43
44
        Geo::index($models->first()->geoIndex())->add($models->map->toCoordinate());
45
46
        event(new ModelsImported($models));
47
    }
48
49
    public function removeGeo($models)
50
    {
51
        if ($models->isEmpty()) {
52
            return;
53
        }
54
55
        Geo::index($models->first()->geoIndex())->remove($models->map->geoKey()->all());
56
57
        event(new ModelsRemoved($models));
58
    }
59
60
    public static function geoImportAll()
61
    {
62
        $self = new static;
63
64
        $self->newQuery()->orderBy($self->geoKeyName())->addGeo();
0 ignored issues
show
Bug introduced by
It seems like newQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
65
    }
66
67
    public static function geoRemoveAll()
68
    {
69
        $self = new static;
70
71
        $self->newQuery()->orderBy($self->geoKeyName())->removeGeo();
0 ignored issues
show
Bug introduced by
It seems like newQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
72
    }
73
74
    public function geoDistanceFrom($model)
75
    {
76
        return [
77
            'unit' => $this->geoUnit,
0 ignored issues
show
Bug introduced by
The property geoUnit does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
78
            'distance' => (float) Geo::between($this->toCoordinate(), $model->toCoordinate()),
79
        ];
80
    }
81
82
    public function scopeGeoNearest($builder, $radius = 10)
83
    {
84
        $locations = array_keys(Geo::index($this->geoIndex())->from($this->toCoordinate(), $radius));
85
86
        $builder->whereIn($this->geoKeyName(), $locations);
87
88 View Code Duplication
        if ($this->databaseDriver() !== 'sqlite') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
            $builder->orderByRaw(DB::raw(sprintf('FIELD(%s,%s)', $this->geoKeyName(), implode(',', $locations))));
90
        }
91
    }
92
93
    public function scopeGeoSearch($builder, $longitude, $latitude, $radius, $sort = 'ASC')
94
    {
95
        $locations = array_keys(Geo::index($this->geoIndex())->search($longitude, $latitude, $radius, $sort));
96
97
        $builder->whereIn($this->geoKeyName(), $locations);
98
99 View Code Duplication
        if ($this->databaseDriver() !== 'sqlite') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
            $builder->orderByRaw(DB::raw(sprintf('FIELD(%s,%s)', $this->geoKeyName(), implode(',', $locations))));
101
        }
102
    }
103
104
    public function getGeoUnitAttribute()
105
    {
106
        return config('geo.unit');
107
    }
108
109
    public function getGeoDistanceAttribute()
110
    {
111
        if ($this->geoEnabled() && array_key_exists($this->geoKey(), $results = Geo::previousGeoSearch($this->geoIndex()))) {
112
            return Arr::get($results, $this->geoKey());
113
        }
114
115
        return 0;
116
    }
117
118
    public function geoEnabled()
119
    {
120
        return $this->geoEnabled;
121
    }
122
123
    public function geoIndex()
124
    {
125
        return $this->getTable();
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
126
    }
127
128
    public function geoKeyName()
129
    {
130
        return $this->getKeyName();
0 ignored issues
show
Bug introduced by
The method getKeyName() does not exist on Leitom\Geo\HasGeoAbilities. Did you maybe mean geoKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
131
    }
132
133
    public function geoKey()
134
    {
135
        return $this->getKey();
0 ignored issues
show
Bug introduced by
It seems like getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
136
    }
137
138
    public function geoLongitude()
139
    {
140
        return $this->longitude;
0 ignored issues
show
Bug introduced by
The property longitude does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
141
    }
142
143
    public function geoLatitude()
144
    {
145
        return $this->latitude;
0 ignored issues
show
Bug introduced by
The property latitude does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
146
    }
147
148
    public function toCoordinate()
149
    {
150
        return new Coordinate($this->geoKey(), $this->geoLongitude(), $this->geoLatitude());
151
    }
152
153
    public function toArray()
154
    {
155
        $attributes = parent::toArray();
156
157
        if ($this->geoEnabled()) {
158
            $attributes['geo_unit'] = $this->geoUnit;
159
            $attributes['geo_distance'] = $this->geoDistance;
0 ignored issues
show
Bug introduced by
The property geoDistance does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
160
        }
161
162
        return $attributes;
163
    }
164
165
    protected function databaseDriver()
166
    {
167
        $connection = config('database.default');
168
169
        return config("database.connections.{$connection}.driver");
170
    }
171
}
172