Completed
Push — master ( 6e8adf...c24137 )
by
unknown
27s
created

Device::getCloseTimeHumanAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 6
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 6
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\SoftDeletes;
7
use Carbon\Carbon;
8
use Illuminate\Support\Facades\Auth;
9
use Spatie\Activitylog\Traits\LogsActivity;
10
11
class Device extends Model
12
{
13
    use SoftDeletes;
14
    use LogsActivity;
15
    //use CausesActivity;
16
    
17
    /**
18
     * The attributes that should be mutated to dates.
19
     *
20
     * @var array
21
     */
22
    protected $dates = [
23
        'deleted_at',
24
        'last_network_update_at'
25
    ];
26
    
27
    /**
28
     * The attributes that should be hidden for arrays.
29
     *
30
     * @var array
31
     */
32
    protected $hidden = [ 'token' ];
33
    
34
    /**
35
     * The attributes that are mass assignable.
36
     *
37
     * @var array
38
     */
39
    protected $fillable = [
40
        'name', 'location_id', 'uuid', 'version', 'hostname', 'ip', 'mac_address', 
41
        'time', 'cover_command', 'cover_status', 'error_msg', 'update_rate',
42
        'image_rate', 'sensor_rate', 'open_time', 'close_time', 'last_network_update_at',
43
    ];
44
    
45
    /**
46
     * The attributes to ignore in the Activity Log
47
     *
48
     * @var array
49
     */
50
    protected static $ignoreChangedAttributes = [ 'updated_at', 'last_network_update_at' ];
51
    
52
    /**
53
     * The attributes to log in the Activity Log
54
     *
55
     * @var array
56
     */
57
    protected static $logAttributes = [
58
        'name', 'location_id', 'uuid', 'version', 'hostname', 'ip', 'mac_address', 
59
        'time', 'cover_command', 'cover_status', 'error_msg',
60
        'update_rate', 'image_rate', 'sensor_rate', 'open_time', 'close_time'
61
    ];
62
    
63
    /**
64
     * Only log those that have actually changed after the update.
65
     *
66
     * @var array
67
     */
68
    protected static $logOnlyDirty = true;
69
    
70
    /**
71
     * Update the updated_at and created_at timestamps?
72
     *
73
     * @var array
74
     */
75
    public $timestamps = true;
76
    
77
    /**
78
     * Get the location for the device
79
     */
80
    public function location()
81
    {
82
        return $this->belongsTo('App\Location', 'location_id');
83
    }
84
    
85
    /**
86
     * Get the site for the device using model accessor
87
     */
88
    public function getSiteAttribute()
89
    {
90
        return $this->location->site ?? (object) [ ];
91
    }
92
    
93
    /**
94
     * Accessor: Get the open time of the device converted to hours and minutes
95
     * If it is a device accessing the time use UTC
96
     * If it is a user accessing the time use their preferred timezone
97
     *
98
     * @param  string $value
99
     * @return string
100
     */
101 View Code Duplication
    public function getOpenTimeAttribute($value)
102
    {
103
        $time = new Carbon($value, 'UTC');
104
        
105
        //If the user is logged in then use there preferred timezone
106
        if (Auth::check()) {
107
                    $time = $time->setTimezone(Auth::user()->timezone);
108
        }
109
110
        return $time->format('H:i');
111
    }
112
    
113
    /**
114
     * Accessor: Get the open time of the device converted to the users preferred time and
115
     * converted to a user friendly format of h:i a
116
     *
117
     * @return string
118
     */
119 View Code Duplication
    public function getOpenTimeHumanAttribute()
120
    {
121
        $time = new Carbon($this->attributes[ 'open_time' ], 'UTC');
122
        $time = $time->setTimezone(Auth::user()->timezone);
123
        
124
        return $time->format('h:i a');
125
    }
126
    
127
    /**
128
     * Accessor: Get the close time of the device converted to hours and minutes
129
     * If it is a device accessing the time use UTC
130
     * If it is a user accessing the time use their preferred timezone
131
     *
132
     * @param  string $value
133
     * @return string
134
     */
135 View Code Duplication
    public function getCloseTimeAttribute($value)
136
    {
137
        $time = new Carbon($value, 'UTC');
138
    
139
        //If the user is logged in then use there preferred timezone
140
        if (Auth::check()) {
141
                    $time = $time->setTimezone(Auth::user()->timezone);
142
        }
143
        
144
        return $time->format('H:i');
145
    }
146
    
147
    /**
148
     * Accessor: Get the close time of the device converted to the users preferred time and
149
     * converted to a user friendly format of h:i a
150
     *
151
     * @return string
152
     */
153 View Code Duplication
    public function getCloseTimeHumanAttribute()
154
    {
155
        $time = new Carbon($this->attributes[ 'close_time' ], 'UTC');
156
        $time = $time->setTimezone(Auth::user()->timezone);
157
        
158
        return $time->format('h:i a');
159
    }
160
    
161
    /**
162
     * Set the open time to UTC
163
     * If it is a device saving the time use UTC
164
     * If it is a user saving the time use their preferred timezone
165
     *
166
     * @param  string  $value
167
     * @return void
168
     */
169 View Code Duplication
    public function setOpenTimeAttribute($value)
170
    {
171
        //If the user is logged in then use there preferred timezone
172
        if (Auth::check())
173
        {
174
            $time = new Carbon($value, Auth::user()->timezone);
175
            $time = $time->setTimezone('UTC');
176
        } else {
177
                    $time = new Carbon($value, 'UTC');
178
        }
179
        
180
        $this->attributes[ 'open_time' ] = $time->format('H:i:s');
181
    }
182
    
183
    /**
184
     * Set the close time to UTC
185
     * If it is a device saving the time use UTC
186
     * If it is a user saving the time use their preferred timezone
187
     *
188
     * @param  string  $value
189
     * @return void
190
     */
191 View Code Duplication
    public function setCloseTimeAttribute($value)
192
    {
193
        //If the user is logged in then use there preferred timezone
194
        if (Auth::check())
195
        {
196
            $time = new Carbon($value, Auth::user()->timezone);
197
            $time = $time->setTimezone('UTC');
198
        } else {
199
                    $time = new Carbon($value, 'UTC');
200
        }
201
        
202
        $this->attributes[ 'close_time' ] = $time->format('H:i:s');
203
    }
204
    
205
    /**
206
     * Accessor: Get the last time the server received an update call from the device in seconds/minutes/hours since
207
     * update or converted to user friendly readable format.
208
     * If the time is less then a day old then display time since it last updated
209
     * If the time is greater then a day old then display the time in the format of Month day, year 12hour:mins am/pm
210
     * and using the user's preferred timezone
211
     *
212
     * @return string
213
     */
214 View Code Duplication
    public function getLastNetworkUpdateAtHumanAttribute()
215
    {
216
        if ($this->last_network_update_at->diffInDays() > 0) {
217
                    return $this->last_network_update_at->setTimezone(Auth::user()->timezone)->format('M d, Y h:i a');
218
        } else {
219
                    return $this->last_network_update_at->diffForHumans();
220
        }
221
    }
222
    
223
    /**
224
     * Accessor: Get the devices last update time in seconds/minutes/hours since update or converted to user friendly
225
     * readable format.
226
     * If the time is less then a day old then display time since it last update
227
     * If the time is greater then a day old then display the time in the format of Month day, year 12hour:mins am/pm
228
     * and using the user's preferred timezone
229
     *
230
     *
231
     * @return string
232
     */
233 View Code Duplication
    public function getUpdatedAtHumanAttribute()
234
    {
235
        if ($this->updated_at->diffInDays() > 0) {
236
                    return $this->updated_at->setTimezone(Auth::user()->timezone)->format('M d, Y h:i a');
237
        } else {
238
                    return $this->updated_at->diffForHumans();
239
        }
240
    }
241
    
242
    /**
243
     * Accessor: Get the devices creation time in seconds/minutes/hours since creation or converted to user friendly
244
     * readable format.
245
     * If the time is less then a day old then display time since its creation
246
     * If the time is greater then a day old then display the time in the format of Month day, year 12hour:mins am/pm
247
     * and using the user's preferred timezone
248
     *
249
     * @return string
250
     */
251 View Code Duplication
    public function getCreatedAtHumanAttribute()
252
    {
253
        if ($this->created_at->diffInDays() > 0) {
254
                    return $this->created_at->setTimezone(Auth::user()->timezone)->format('M d, Y h:i a');
255
        } else {
256
                    return $this->created_at->diffForHumans();
257
        }
258
    }
259
    
260
    /**
261
     * Scope a query to only include devices belonging to a given location
262
     *
263
     * @param \Illuminate\Database\Eloquent\Builder $query
264
     * @param int $location_id
265
     * @return \Illuminate\Database\Eloquent\Builder
266
     */
267
    public function scopeByLocation($query, $location_id)
268
    {
269
        return $query->where('location_id', $location_id);
270
    }
271
    
272
    /**
273
     * Scope a query to limit the included columns to only include what is publicly needed to be displayed on the
274
     * dashboard
275
     *
276
     * @param \Illuminate\Database\Eloquent\Builder $query
277
     * @return \Illuminate\Database\Eloquent\Builder
278
     */
279
    public function scopePublicDashData($query)
280
    {
281
        return $query->select([
0 ignored issues
show
Bug Best Practice introduced by
The expression return $query->select(ar... as image_updated_at')) also could return the type Illuminate\Database\Query\Builder which is incompatible with the documented return type Illuminate\Database\Eloquent\Builder.
Loading history...
282
            'devices.id',
283
            'name',
284
            'location_id',
285
            'cover_command',
286
            'cover_status',
287
            'open_time',
288
            'close_time',
289
            'update_rate',
290
            'image_rate',
291
            'sensor_rate',
292
            'last_network_update_at',
293
            'image.updated_at as image_updated_at',
294
        ]);
295
    }
296
    
297
    /**
298
     * Create a new API token for the device.
299
     */
300
    public function generateToken()
301
    {
302
        $this->token = str_random(60);
303
        $this->save();
304
        
305
        return $this->token;
306
    }
307
    
308
    /**
309
     * Get a device by uuid
310
     *
311
     * @param string $uuid
312
     * @return Device|Illuminate\Database\Eloquent\Model
0 ignored issues
show
Bug introduced by
The type App\Illuminate\Database\Eloquent\Model was not found. Did you mean Illuminate\Database\Eloquent\Model? If so, make sure to prefix the type with \.
Loading history...
313
     */
314
    public static function getDeviceByUUID($uuid)
315
    {
316
        return self::where('uuid', $uuid)->first();
317
    }
318
    
319
    /**
320
     * Get the deviceimage record associated with the device.
321
     */
322
    public function image()
323
    {
324
        return $this->hasOne('App\Deviceimage');
325
    }
326
    
327
328
    /**
329
     * Get the sensors associated with the device.
330
     */
331
    public function sensors()
332
    {
333
        return $this->hasMany('App\Sensor');
334
    }
335
    
336
    /**
337
     * Get the sensor data associated with the device.
338
     */
339
    public function data()
340
    {
341
        return $this->hasManyThrough('App\SensorData', 'App\Sensor');
342
    }
343
    
344
    /**
345
     * Check if the device is ready for a cover command
346
     *
347
     * @return boolean
348
     */
349
    public function isReadyForCommand()
350
    {
351
        return ($this->cover_status == 'open' || $this->cover_status == 'closed' || $this->cover_status == 'locked');
352
    }
353
    
354
    /**
355
     * Check if the current time is during the devices scheduled time to be open
356
     *
357
     * @return boolean
358
     */
359
    public function isDuringScheduleOpen()
360
    {
361
        $timezone = Auth::user()->timezone;
362
        //Get the open, close, and current time in the users timezone
363
        $open_time = new Carbon($this->open_time, $timezone);
364
        $close_time = new Carbon($this->close_time, $timezone);
365
        $time_now = Carbon::now($timezone);
366
    
367
        //Check if the current time is during the open schedule or not
368
        if ($time_now->gt($open_time) && $time_now->lt($close_time)) {
369
                    return true;
370
        } else {
371
                    return false;
372
        }
373
    }
374
    
375
    /**
376
     * Get the covers actual status based on the current command and the devices status
377
     *
378
     * @return string
379
     */
380
    public function actualCoverStatus()
381
    {
382
        $isOpen = $this->cover_status === 'open';
383
        $isClosed = $this->cover_status === 'closed';
384
        $isLocked = $this->cover_status === 'locked';
385
            
386
        switch ($this[ 'cover_command' ])
387
        {
388
            case 'open':
389
                if ($isOpen) {
390
                                    $status = 'open';
391
                } else if ($isLocked) {
392
                                    $status = 'unlocking';
393
                } else {
394
                                    $status = 'opening';
395
                }
396
                break;
397
            case 'close':
398
                if ($isClosed) {
399
                                    $status = 'closed';
400
                } else if ($isLocked) {
401
                                    $status = 'unlocking';
402
                } else {
403
                                    $status = 'closing';
404
                }
405
                break;
406
            case 'lock':
407
                $status = 'locked';
408
                break;
409
            default:
410
                $status = 'error';
411
        }
412
    
413
        if ($this->cover_status === 'error') {
414
                    $status = 'error';
415
        }
416
        
417
        return $status;
418
    }
419
    
420
    /**
421
     * Get the page number of the device for the dashboard device table pagination
422
     *
423
     * @param int $limit
424
     * @return double
425
     */
426
    public function dashPageNum($limit)
427
    {
428
        $pos = Device::where('location_id', '=', $this->location_id)
429
            ->where('name', '<=', $this->name)
430
            ->orderBy('name', 'ASC')
431
            ->count();
432
        
433
        return ceil($pos / $limit);
434
    }
435
}
436