1 | <?php |
||
8 | class ListHosts extends BaseCommand |
||
9 | { |
||
10 | protected $signature = 'monitor:list |
||
11 | {--host= : Filter hosts by name} |
||
12 | {--check= : Filter checks by type}'; |
||
13 | |||
14 | protected $description = 'List all hosts with their checks'; |
||
15 | |||
16 | public function handle() |
||
17 | { |
||
18 | $hostName = $this->option('host'); |
||
19 | $checkType = $this->option('check'); |
||
20 | |||
21 | $hostsQuery = Host::query(); |
||
22 | |||
23 | if ($hostName) { |
||
24 | $hostsQuery->where('name', 'LIKE', "%{$hostName}%"); |
||
25 | } |
||
26 | |||
27 | if ($checkType) { |
||
28 | $hostsQuery |
||
|
|||
29 | ->whereHas('checks', function ($query) use ($checkType) { |
||
30 | $query->where('type', 'LIKE', "%{$checkType}%"); |
||
31 | }) |
||
32 | ->with(['checks' => function ($query) use ($checkType) { |
||
33 | $query->where('type', 'LIKE', "%{$checkType}%"); |
||
34 | }]); |
||
35 | } |
||
36 | |||
37 | $hosts = $hostsQuery->get(); |
||
38 | |||
39 | $this->renderTable($hosts); |
||
40 | } |
||
41 | |||
42 | protected function renderTable($hosts) |
||
43 | { |
||
44 | $rows = $hosts->map(function ($host) { |
||
45 | $name = $host->name; |
||
46 | |||
47 | $checks = $this->formatCheckStatusCountForHost($host); |
||
48 | |||
49 | $messages = $this->formatCheckMessagesForHost($host); |
||
50 | |||
51 | return compact('name', 'checks', 'messages'); |
||
52 | }); |
||
53 | |||
54 | $header = ['Host', 'Checks', 'Message']; |
||
55 | |||
56 | $this->table($header, $rows); |
||
57 | } |
||
58 | |||
59 | protected function formatCheckStatusCountForHost(Host $host): string |
||
60 | { |
||
61 | $statuses = collect([CheckStatus::SUCCESS, CheckStatus::FAILED, CheckStatus::NOT_YET_CHECKED, CheckStatus::WARNING]); |
||
62 | |||
63 | $checks = $statuses |
||
64 | ->map(function ($status) use ($host) { |
||
65 | $checksWithStatus = $host->checks->where('status', $status); |
||
66 | $statusCount = $checksWithStatus->count(); |
||
67 | $emoji = $checksWithStatus->first()->statusAsEmoji ?? ''; |
||
68 | |||
69 | return $statusCount ? "{$emoji} {$statusCount} " : ''; |
||
70 | }) |
||
71 | ->implode(''); |
||
72 | |||
73 | return substr($checks, 0, -2); |
||
74 | } |
||
75 | |||
76 | protected function formatCheckMessagesForHost(Host $host): string |
||
87 | } |
||
88 |
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: