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
|
|
|
|
14
|
|
|
class SiteCollection extends Collection |
15
|
|
|
{ |
16
|
|
|
public function checkUptime() |
17
|
|
|
{ |
18
|
|
|
$this->resetItemKeys(); |
19
|
|
|
|
20
|
|
|
(new EachPromise($this->getPromises(), [ |
21
|
|
|
'concurrency' => 100, |
22
|
|
|
'fulfilled' => function (ResponseInterface $response, $index) { |
23
|
|
|
$site = $this->items[$index]; |
24
|
|
|
|
25
|
|
|
consoleOutput()->info("Could reach {$site->url}"); |
|
|
|
|
26
|
|
|
|
27
|
|
|
$site->pingSucceeded($response->getBody()); |
28
|
|
|
}, |
29
|
|
|
|
30
|
|
|
'rejected' => function (RequestException $exception, $index) { |
31
|
|
|
$site = $this->items[$index]; |
32
|
|
|
|
33
|
|
|
consoleOutput()->error("Could not reach {$site->url} error: `{$exception->getMessage()}`"); |
|
|
|
|
34
|
|
|
|
35
|
|
|
$site->pingFailed($exception->getMessage()); |
36
|
|
|
}, |
37
|
|
|
]))->promise()->wait(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
protected function getPromises() : Generator |
41
|
|
|
{ |
42
|
|
|
$client = new Client([ |
43
|
|
|
'headers' => [ |
44
|
|
|
'User-Agent' => 'spatie/laravel-uptime-monitor uptime checker', |
45
|
|
|
], |
46
|
|
|
]); |
47
|
|
|
|
48
|
|
|
foreach ($this->items as $site) { |
49
|
|
|
consoleOutput()->info("checking {$site->url}"); |
|
|
|
|
50
|
|
|
|
51
|
|
|
$promise = $client->requestAsync( |
52
|
|
|
$site->getPingRequestMethod(), |
53
|
|
|
$site->url, |
54
|
|
|
['connect_timeout' => 10] |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
yield $promise; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Make sure the keys are in consecutive order without gaps. |
63
|
|
|
*/ |
64
|
|
|
protected function resetItemKeys() |
65
|
|
|
{ |
66
|
|
|
$this->items = $this->values()->all(); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
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: