Completed
Push — develop ( bad89c...4b21ec )
by Abdelrahman
10:54
created

Address::getFullNameAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Addresses\Models;
6
7
use Illuminate\Database\Eloquent\Model;
8
use Rinvex\Cacheable\CacheableEloquent;
9
use Illuminate\Database\Eloquent\Builder;
10
use Jackpopp\GeoDistance\GeoDistanceTrait;
11
use Rinvex\Support\Traits\ValidatingTrait;
12
use Illuminate\Database\Eloquent\Relations\MorphTo;
13
14
/**
15
 * Rinvex\Addresses\Models\Address.
16
 *
17
 * @property int                                                $id
18
 * @property int                                                $addressable_id
19
 * @property string                                             $addressable_type
20
 * @property string                                             $label
21
 * @property string                                             $given_name
22
 * @property string                                             $family_name
23
 * @property string                                             $full_name
24
 * @property string                                             $organization
25
 * @property string                                             $country_code
26
 * @property string                                             $street
27
 * @property string                                             $state
28
 * @property string                                             $city
29
 * @property string                                             $postal_code
30
 * @property float                                              $latitude
31
 * @property float                                              $longitude
32
 * @property bool                                               $is_primary
33
 * @property bool                                               $is_billing
34
 * @property bool                                               $is_shipping
35
 * @property \Carbon\Carbon|null                                $created_at
36
 * @property \Carbon\Carbon|null                                $updated_at
37
 * @property-read \Illuminate\Database\Eloquent\Model|\Eloquent $addressable
38
 *
39
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address inCountry($countryCode)
40
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address inLanguage($languageCode)
41
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address isBilling()
42
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address isPrimary()
43
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address isShipping()
44
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address outside($distance, $measurement = null, $latitude = null, $longitude = null)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 165 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
45
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereAddressableId($value)
46
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereAddressableType($value)
47
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereCity($value)
48
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereCountryCode($value)
49
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereCreatedAt($value)
50
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereFamilyName($value)
51
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereGivenName($value)
52
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereId($value)
53
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereIsBilling($value)
54
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereIsPrimary($value)
55
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereIsShipping($value)
56
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereLabel($value)
57
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereLatitude($value)
58
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereLongitude($value)
59
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereOrganization($value)
60
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address wherePostalCode($value)
61
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereState($value)
62
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereStreet($value)
63
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address whereUpdatedAt($value)
64
 * @method static \Illuminate\Database\Eloquent\Builder|\Rinvex\Addresses\Models\Address within($distance, $measurement = null, $latitude = null, $longitude = null)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 164 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
65
 * @mixin \Eloquent
66
 */
67
class Address extends Model
68
{
69
    use ValidatingTrait;
70
    use GeoDistanceTrait;
71
    use CacheableEloquent;
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    protected $fillable = [
77
        'addressable_id',
78
        'addressable_type',
79
        'label',
80
        'given_name',
81
        'family_name',
82
        'organization',
83
        'country_code',
84
        'street',
85
        'state',
86
        'city',
87
        'postal_code',
88
        'latitude',
89
        'longitude',
90
        'is_primary',
91
        'is_billing',
92
        'is_shipping',
93
    ];
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    protected $casts = [
99
        'addressable_id' => 'integer',
100
        'addressable_type' => 'string',
101
        'label' => 'string',
102
        'given_name' => 'string',
103
        'family_name' => 'string',
104
        'organization' => 'string',
105
        'country_code' => 'string',
106
        'street' => 'string',
107
        'state' => 'string',
108
        'city' => 'string',
109
        'postal_code' => 'string',
110
        'latitude' => 'float',
111
        'longitude' => 'float',
112
        'is_primary' => 'boolean',
113
        'is_billing' => 'boolean',
114
        'is_shipping' => 'boolean',
115
        'deleted_at' => 'datetime',
116
    ];
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    protected $observables = [
122
        'validating',
123
        'validated',
124
    ];
125
126
    /**
127
     * The default rules that the model will validate against.
128
     *
129
     * @var array
130
     */
131
    protected $rules = [
132
        'addressable_id' => 'required|integer',
133
        'addressable_type' => 'required|string|max:150',
134
        'label' => 'nullable|string|max:150',
135
        'given_name' => 'required|string|max:150',
136
        'family_name' => 'nullable|string|max:150',
137
        'organization' => 'nullable|string|max:150',
138
        'country_code' => 'nullable|alpha|size:2|country',
139
        'street' => 'nullable|string|max:150',
140
        'state' => 'nullable|string|max:150',
141
        'city' => 'nullable|string|max:150',
142
        'postal_code' => 'nullable|string|max:150',
143
        'latitude' => 'nullable|numeric',
144
        'longitude' => 'nullable|numeric',
145
        'is_primary' => 'sometimes|boolean',
146
        'is_billing' => 'sometimes|boolean',
147
        'is_shipping' => 'sometimes|boolean',
148
    ];
149
150
    /**
151
     * Whether the model should throw a
152
     * ValidationException if it fails validation.
153
     *
154
     * @var bool
155
     */
156
    protected $throwValidationExceptions = true;
157
158
    /**
159
     * Create a new Eloquent model instance.
160
     *
161
     * @param array $attributes
162
     */
163
    public function __construct(array $attributes = [])
164
    {
165
        parent::__construct($attributes);
166
167
        $this->setTable(config('rinvex.addresses.tables.addresses'));
168
    }
169
170
    /**
171
     * Get the owner model of the address.
172
     *
173
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
174
     */
175
    public function addressable(): MorphTo
176
    {
177
        return $this->morphTo('addressable', 'addressable_type', 'addressable_id');
178
    }
179
180
    /**
181
     * Scope primary addresses.
182
     *
183
     * @param \Illuminate\Database\Eloquent\Builder $builder
184
     *
185
     * @return \Illuminate\Database\Eloquent\Builder
186
     */
187
    public function scopeIsPrimary(Builder $builder): Builder
188
    {
189
        return $builder->where('is_primary', true);
190
    }
191
192
    /**
193
     * Scope billing addresses.
194
     *
195
     * @param \Illuminate\Database\Eloquent\Builder $builder
196
     *
197
     * @return \Illuminate\Database\Eloquent\Builder
198
     */
199
    public function scopeIsBilling(Builder $builder): Builder
200
    {
201
        return $builder->where('is_billing', true);
202
    }
203
204
    /**
205
     * Scope shipping addresses.
206
     *
207
     * @param \Illuminate\Database\Eloquent\Builder $builder
208
     *
209
     * @return \Illuminate\Database\Eloquent\Builder
210
     */
211
    public function scopeIsShipping(Builder $builder): Builder
212
    {
213
        return $builder->where('is_shipping', true);
214
    }
215
216
    /**
217
     * Scope addresses by the given country.
218
     *
219
     * @param \Illuminate\Database\Eloquent\Builder $builder
220
     * @param string                                $countryCode
221
     *
222
     * @return \Illuminate\Database\Eloquent\Builder
223
     */
224
    public function scopeInCountry(Builder $builder, string $countryCode): Builder
225
    {
226
        return $builder->where('country_code', $countryCode);
227
    }
228
229
    /**
230
     * Scope addresses by the given language.
231
     *
232
     * @param \Illuminate\Database\Eloquent\Builder $builder
233
     * @param string                                $languageCode
234
     *
235
     * @return \Illuminate\Database\Eloquent\Builder
236
     */
237
    public function scopeInLanguage(Builder $builder, string $languageCode): Builder
238
    {
239
        return $builder->where('language_code', $languageCode);
240
    }
241
242
    /**
243
     * Get full name attribute.
244
     *
245
     * @return string
246
     */
247
    public function getFullNameAttribute(): string
248
    {
249
        return implode(' ', [$this->given_name, $this->family_name]);
250
    }
251
252
    /**
253
     * {@inheritdoc}
254
     */
255
    protected static function boot()
256
    {
257
        parent::boot();
258
259
        static::saving(function (self $address) {
260
            if (config('rinvex.addresses.geocoding')) {
261
                $segments[] = $address->street;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$segments was never initialized. Although not strictly required by PHP, it is generally a good practice to add $segments = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
262
                $segments[] = sprintf('%s, %s %s', $address->city, $address->state, $address->postal_code);
263
                $segments[] = country($address->country_code)->getName();
264
265
                $query = str_replace(' ', '+', implode(', ', $segments));
266
                $geocode = json_decode(file_get_contents("https://maps.google.com/maps/api/geocode/json?address={$query}&sensor=false"));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 137 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
267
268
                if (count($geocode->results)) {
269
                    $address->latitude = $geocode->results[0]->geometry->location->lat;
270
                    $address->longitude = $geocode->results[0]->geometry->location->lng;
271
                }
272
            }
273
        });
274
    }
275
}
276