Host::isUnhealthy()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\ServerMonitor\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\HasMany;
7
use Illuminate\Support\Collection;
8
use Spatie\ServerMonitor\Models\Concerns\HasCustomProperties;
9
use Spatie\ServerMonitor\Models\Enums\CheckStatus;
10
use Spatie\ServerMonitor\Models\Enums\HostHealth;
11
use Spatie\ServerMonitor\Models\Presenters\HostPresenter;
12
13
class Host extends Model
14
{
15
    use HostPresenter, HasCustomProperties;
16
17
    public $casts = [
18
        'custom_properties' => 'array',
19
    ];
20
21
    public $guarded = [];
22
23
    public function checks(): HasMany
24
    {
25
        return $this->hasMany(config('server-monitor.check_model', Check::class));
26
    }
27
28
    public function getEnabledChecksAttribute(): Collection
29
    {
30
        return $this->checks()->enabled()->get();
31
    }
32
33
    public function isHealthy(): bool
34
    {
35
        return $this->status === HostHealth::HEALTHY;
36
    }
37
38
    public function isUnhealthy(): bool
39
    {
40
        return $this->status === HostHealth::UNHEALTHY;
41
    }
42
43
    public function hasWarning(): bool
44
    {
45
        return $this->status === HostHealth::WARNING;
46
    }
47
48
    public function getStatusAttribute(): string
49
    {
50
        if ($this->enabled_checks->count() === 0) {
51
            return HostHealth::WARNING;
52
        }
53
54
        if ($this->enabled_checks->contains->hasStatus(CheckStatus::FAILED)) {
55
            return HostHealth::UNHEALTHY;
56
        }
57
58
        if ($this->enabled_checks->every->hasStatus(CheckStatus::SUCCESS)) {
59
            return HostHealth::HEALTHY;
60
        }
61
62
        return HostHealth::WARNING;
63
    }
64
65
    public function hasCheckType(string $type): bool
66
    {
67
        return $this->checks->contains(function (Check $check) use ($type) {
68
            return $check->type === $type;
69
        });
70
    }
71
}
72