1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ServerMonitor\Commands; |
4
|
|
|
|
5
|
|
|
use File; |
6
|
|
|
use Spatie\ServerMonitor\Models\Host; |
7
|
|
|
use Spatie\ServerMonitor\Models\Check; |
8
|
|
|
|
9
|
|
|
class SyncFile extends BaseCommand |
10
|
|
|
{ |
11
|
|
|
protected $signature = 'server-monitor:sync-file |
12
|
|
|
{filename : JSON file with hosts} |
13
|
|
|
{--delete-missing : Delete hosts from the database that are not in the hosts file}'; |
14
|
|
|
|
15
|
|
|
protected $description = 'One way sync hosts from JSON file to database'; |
16
|
|
|
|
17
|
|
|
public function handle() |
18
|
|
|
{ |
19
|
|
|
$json = File::get($this->argument('filename')); |
|
|
|
|
20
|
|
|
|
21
|
|
|
$hostsInFile = collect(json_decode($json, true)); |
22
|
|
|
|
23
|
|
|
$this->updateOrCreateHosts($hostsInFile); |
24
|
|
|
|
25
|
|
|
$this->deleteMissingHosts($hostsInFile); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param $hostsInFile |
30
|
|
|
*/ |
31
|
|
|
protected function deleteMissingHosts($hostsInFile) |
32
|
|
|
{ |
33
|
|
|
if ($this->option('delete-missing')) { |
34
|
|
|
Host::all()->each(function (Host $host) use ($hostsInFile) { |
35
|
|
|
if (! $hostsInFile->contains('name', $host->name)) { |
|
|
|
|
36
|
|
|
$this->comment("Deleted host '{$host->name}' from database (was not found in hosts file)"); |
|
|
|
|
37
|
|
|
$host->delete(); |
38
|
|
|
} |
39
|
|
|
}); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param $hostsInFile |
45
|
|
|
*/ |
46
|
|
|
protected function updateOrCreateHosts($hostsInFile) |
47
|
|
|
{ |
48
|
|
|
$hostsInFile->each(function ($host) { |
49
|
|
|
$host = collect($host); |
50
|
|
|
|
51
|
|
|
$hostModel = Host::firstOrNew(['name' => $host['name']]); |
52
|
|
|
|
53
|
|
|
$hostModel |
54
|
|
|
->fill($host->except('checks')->toArray()) |
55
|
|
|
->save(); |
56
|
|
|
|
57
|
|
|
// Delete checks that were deleted from the file |
58
|
|
|
$hostModel->checks->each(function (Check $check) use ($host) { |
59
|
|
|
if (! in_array($check->type, $host['checks'])) { |
|
|
|
|
60
|
|
|
$this->comment("Deleted '{$check->type}' from host '{$host['name']}' (not found in hosts file)"); |
|
|
|
|
61
|
|
|
$check->delete(); |
62
|
|
|
} |
63
|
|
|
}); |
64
|
|
|
|
65
|
|
|
// Add checks that do not exist in db |
66
|
|
|
foreach ($host['checks'] as $check) { |
67
|
|
|
if ($hostModel->checks->where('type', $check)->count() === 0) { |
68
|
|
|
$hostModel->checks()->create(['type' => $check]); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
}); |
72
|
|
|
|
73
|
|
|
$this->info("Synced {$hostsInFile->count()} host(s) to database"); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.