1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor\Models; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor; |
7
|
|
|
use Spatie\UptimeMonitor\Models\Enums\SslCertificateStatus; |
8
|
|
|
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus; |
9
|
|
|
use Spatie\UptimeMonitor\Models\Presenters\MonitorPresenter; |
10
|
|
|
use Spatie\UptimeMonitor\Models\Traits\SupportsSslCertificateCheck; |
11
|
|
|
use Spatie\UptimeMonitor\Models\Traits\SupportsUptimeCheck; |
12
|
|
|
use Spatie\Url\Url; |
13
|
|
|
|
14
|
|
|
class Monitor extends Model |
15
|
|
|
{ |
16
|
|
|
use SupportsUptimeCheck, |
17
|
|
|
SupportsSslCertificateCheck, |
18
|
|
|
MonitorPresenter; |
19
|
|
|
|
20
|
|
|
protected $guarded = []; |
21
|
|
|
|
22
|
|
|
protected $dates = [ |
23
|
|
|
'uptime_last_check_date', |
24
|
|
|
'uptime_status_last_change_date', |
25
|
|
|
'down_event_fired_on_date', |
26
|
|
|
'ssl_certificate_expiration_date', |
27
|
|
|
]; |
28
|
|
|
|
29
|
|
|
protected $casts = [ |
30
|
|
|
'enabled' => 'boolean', |
31
|
|
|
'check_ssl_certificate' => 'boolean', |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
public function scopeEnabled($query) |
35
|
|
|
{ |
36
|
|
|
return $query->where('enabled', true); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function getUrlAttribute() |
40
|
|
|
{ |
41
|
|
|
if (! isset($this->attributes['url'])) { |
42
|
|
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return Url::fromString($this->attributes['url']); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public static function boot() |
49
|
|
|
{ |
50
|
|
|
parent::boot(); |
51
|
|
|
|
52
|
|
|
static::saving(function (Monitor $monitor) { |
53
|
|
|
if (static::alreadyExists($monitor)) { |
54
|
|
|
throw CannotSaveMonitor::alreadyExists($monitor); |
55
|
|
|
} |
56
|
|
|
}); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function isHealthy() |
60
|
|
|
{ |
61
|
|
|
if (in_array($this->uptime_status, [UptimeStatus::DOWN, UptimeStatus::NOT_YET_CHECKED])) { |
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if ($this->check_ssl_certificate && $this->ssl_certificate_status === SslCertificateStatus::INVALID) { |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return true; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected static function alreadyExists(Monitor $monitor): bool |
73
|
|
|
{ |
74
|
|
|
$query = static::where('url', $monitor->url); |
75
|
|
|
|
76
|
|
|
if ($monitor->exists) { |
77
|
|
|
$query->where('id', '<>', $monitor->id); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return (bool) $query->first(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|