1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor\Commands; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
6
|
|
|
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor; |
7
|
|
|
use Spatie\UptimeMonitor\Models\Monitor; |
8
|
|
|
|
9
|
|
|
class SyncFile extends BaseCommand |
10
|
|
|
{ |
11
|
|
|
protected $signature = 'monitor:sync-file |
12
|
|
|
{path : Path to JSON file with monitors} |
13
|
|
|
{--delete-missing : Delete monitors from the database if they\'re not found in the monitors file}'; |
14
|
|
|
|
15
|
|
|
protected $description = 'One way sync monitors from JSON file to database'; |
16
|
|
|
|
17
|
|
|
public function handle() |
18
|
|
|
{ |
19
|
|
|
$json = file_get_contents($this->argument('path')); |
20
|
|
|
|
21
|
|
|
$monitorsInFile = collect(json_decode($json, true)); |
22
|
|
|
|
23
|
|
|
$this->validateMonitors($monitorsInFile); |
24
|
|
|
|
25
|
|
|
$this->createOrUpdateMonitorsFromFile($monitorsInFile); |
26
|
|
|
|
27
|
|
|
$this->deleteMissingMonitors($monitorsInFile); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
protected function validateMonitors($monitorsInFile) |
31
|
|
|
{ |
32
|
|
|
$monitorsInFile->each(function ($monitorAttributes) { |
33
|
|
|
if (! Str::startsWith($monitorAttributes['url'], ['https://', 'http://'])) { |
34
|
|
|
throw new CannotSaveMonitor("URL `{$monitorAttributes['url']}` is invalid (is the URL scheme included?)"); |
35
|
|
|
} |
36
|
|
|
}); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function createOrUpdateMonitorsFromFile($monitorsInFile) |
40
|
|
|
{ |
41
|
|
|
$monitorsInFile |
42
|
|
|
->each(function ($monitorAttributes) { |
43
|
|
|
$this->createOrUpdateMonitor($monitorAttributes); |
44
|
|
|
}); |
45
|
|
|
|
46
|
|
|
$this->info("Synced {$monitorsInFile->count()} monitor(s) to database"); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function createOrUpdateMonitor(array $monitorAttributes) |
50
|
|
|
{ |
51
|
|
|
Monitor::firstOrNew([ |
52
|
|
|
'url' => $monitorAttributes['url'], |
53
|
|
|
]) |
54
|
|
|
->fill($monitorAttributes) |
55
|
|
|
->save(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function deleteMissingMonitors($monitorsInFile) |
59
|
|
|
{ |
60
|
|
|
if (! $this->option('delete-missing')) { |
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
Monitor::all() |
65
|
|
|
->reject(function (Monitor $monitor) use ($monitorsInFile) { |
66
|
|
|
return $monitorsInFile->contains('url', $monitor->url); |
67
|
|
|
}) |
68
|
|
|
->each(function (Monitor $monitor) { |
69
|
|
|
$path = $this->argument('path'); |
70
|
|
|
$this->comment("Deleted monitor for `{$monitor->url}` from database because it was not found in `{$path}`"); |
71
|
|
|
$monitor->delete(); |
72
|
|
|
}); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|