|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor\Services\PingMonitors; |
|
4
|
|
|
|
|
5
|
|
|
use Cache; |
|
6
|
|
|
use Generator; |
|
7
|
|
|
use GuzzleHttp\Client; |
|
8
|
|
|
use GuzzleHttp\Exception\RequestException; |
|
9
|
|
|
use GuzzleHttp\Promise\EachPromise; |
|
10
|
|
|
use Illuminate\Support\Collection; |
|
11
|
|
|
use Log; |
|
12
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
13
|
|
|
use Spatie\UptimeMonitor\Models\UptimeMonitor; |
|
14
|
|
|
|
|
15
|
|
|
class UptimeMonitorCollection extends Collection |
|
16
|
|
|
{ |
|
17
|
|
|
public function check() |
|
18
|
|
|
{ |
|
19
|
|
|
$this->resetItemKeys(); |
|
20
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
(new EachPromise($this->getPromises(), [ |
|
24
|
|
|
'concurrency' => 100, |
|
25
|
|
|
'fulfilled' => function (ResponseInterface $response, $index) { |
|
26
|
|
|
$uptimeMonitor = $this->items[$index]; |
|
27
|
|
|
|
|
28
|
|
|
consoleOutput()->info("Could reach {$uptimeMonitor->url}"); |
|
|
|
|
|
|
29
|
|
|
|
|
30
|
|
|
$uptimeMonitor->pingSucceeded($response->getBody()); |
|
31
|
|
|
}, |
|
32
|
|
|
|
|
33
|
|
|
'rejected' => function (RequestException $exception, $index) { |
|
34
|
|
|
$uptimeMonitor = $this->items[$index]; |
|
35
|
|
|
|
|
36
|
|
|
consoleOutput()->error("Could not reach {$uptimeMonitor->url} error: `{$exception->getMessage()}`"); |
|
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
$uptimeMonitor->pingFailed($exception->getMessage()); |
|
39
|
|
|
}, |
|
40
|
|
|
]))->promise()->wait(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
protected function getPromises() : Generator |
|
44
|
|
|
{ |
|
45
|
|
|
$client = new Client([ |
|
46
|
|
|
'headers' => [ |
|
47
|
|
|
'User-Agent' => 'spatie/laravel-uptime-monitor uptime checker', |
|
48
|
|
|
], |
|
49
|
|
|
]); |
|
50
|
|
|
|
|
51
|
|
|
foreach ($this->items as $uptimeMonitor) { |
|
52
|
|
|
consoleOutput()->info("checking {$uptimeMonitor->url}"); |
|
|
|
|
|
|
53
|
|
|
|
|
54
|
|
|
$promise = $client->requestAsync( |
|
55
|
|
|
$uptimeMonitor->getPingRequestMethod(), |
|
56
|
|
|
$uptimeMonitor->url, |
|
57
|
|
|
['connect_timeout' => 10] |
|
58
|
|
|
); |
|
59
|
|
|
|
|
60
|
|
|
yield $promise; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Make sure the keys are in consecutive order without gaps. |
|
66
|
|
|
*/ |
|
67
|
|
|
protected function resetItemKeys() |
|
68
|
|
|
{ |
|
69
|
|
|
$this->items = $this->values()->all(); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
If you implement
__calland you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.This is often the case, when
__callis implemented by a parent class and only the child class knows which methods exist: