1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\UptimeMonitor; |
4
|
|
|
|
5
|
|
|
use Generator; |
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
use GuzzleHttp\Exception\RequestException; |
8
|
|
|
use GuzzleHttp\Promise\EachPromise; |
9
|
|
|
use Illuminate\Support\Collection; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
|
12
|
|
|
class SiteCollection extends Collection |
13
|
|
|
{ |
14
|
|
|
public function checkUptime() |
15
|
|
|
{ |
16
|
|
|
$this->resetItemKeys(); |
17
|
|
|
|
18
|
|
|
(new EachPromise($this->getPromises(), [ |
19
|
|
|
'concurrency' => config('laravel-uptime-monitor.concurrent_uptime_checks'), |
20
|
|
|
'fulfilled' => function (ResponseInterface $response, $index) { |
21
|
|
|
$site = $this->items[$index]; |
22
|
|
|
|
23
|
|
|
uptimeMonitorConsoleOutput()->info("Could reach {$site->url}"); |
|
|
|
|
24
|
|
|
|
25
|
|
|
$site->pingSucceeded($response->getBody()); |
26
|
|
|
}, |
27
|
|
|
|
28
|
|
|
'rejected' => function (RequestException $exception, $index) { |
29
|
|
|
$site = $this->items[$index]; |
30
|
|
|
|
31
|
|
|
uptimeMonitorConsoleOutput()->error("Could not reach {$site->url} error: `{$exception->getMessage()}`"); |
|
|
|
|
32
|
|
|
|
33
|
|
|
$site->pingFailed($exception->getMessage()); |
34
|
|
|
}, |
35
|
|
|
]))->promise()->wait(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
protected function getPromises() : Generator |
39
|
|
|
{ |
40
|
|
|
$client = new Client([ |
41
|
|
|
'headers' => [ |
42
|
|
|
'User-Agent' => 'spatie/laravel-uptime-monitor uptime checker', |
43
|
|
|
], |
44
|
|
|
]); |
45
|
|
|
|
46
|
|
|
foreach ($this->items as $site) { |
47
|
|
|
uptimeMonitorConsoleOutput()->info("checking {$site->url}"); |
|
|
|
|
48
|
|
|
|
49
|
|
|
$promise = $client->requestAsync( |
50
|
|
|
$site->uptime_check_method, |
51
|
|
|
$site->url, |
52
|
|
|
['connect_timeout' => 10] |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
yield $promise; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Make sure the keys are in consecutive order without gaps. |
61
|
|
|
*/ |
62
|
|
|
protected function resetItemKeys() |
63
|
|
|
{ |
64
|
|
|
$this->items = $this->values()->all(); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
If you implement
__call
and 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
__call
is implemented by a parent class and only the child class knows which methods exist: