|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Cachet\Data\Checks; |
| 4 | + |
| 5 | +use Cachet\Data\BaseData; |
| 6 | +use Cachet\Enums\ComponentStatusEnum; |
| 7 | +use Illuminate\Http\Client\ConnectionException; |
| 8 | +use Illuminate\Http\Client\RequestException; |
| 9 | +use Illuminate\Http\Client\Response; |
| 10 | + |
| 11 | +final class CheckResult extends BaseData |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + public readonly ComponentStatusEnum $status, |
| 15 | + public readonly bool $successful, |
| 16 | + public readonly ?int $responseCode = null, |
| 17 | + public readonly ?int $responseTime = null, |
| 18 | + public readonly ?string $error = null, |
| 19 | + ) {} |
| 20 | + |
| 21 | + /** |
| 22 | + * Build a check result from a successful HTTP exchange. |
| 23 | + */ |
| 24 | + public static function fromResponse(Response $response, int $attempts, ?float $transferTime = null): self |
| 25 | + { |
| 26 | + $status = match (true) { |
| 27 | + $response->successful() && $attempts === 1 => ComponentStatusEnum::operational, |
| 28 | + $response->successful() => ComponentStatusEnum::performance_issues, |
| 29 | + $response->status() >= 500 => ComponentStatusEnum::major_outage, |
| 30 | + $response->status() >= 400 => ComponentStatusEnum::partial_outage, |
| 31 | + default => ComponentStatusEnum::operational, |
| 32 | + }; |
| 33 | + |
| 34 | + return new self( |
| 35 | + status: $status, |
| 36 | + successful: $response->successful(), |
| 37 | + responseCode: $response->status(), |
| 38 | + responseTime: $transferTime !== null ? (int) round($transferTime * 1000) : null, |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Build a check result from a failed HTTP request. |
| 44 | + */ |
| 45 | + public static function fromException(RequestException|ConnectionException $e): self |
| 46 | + { |
| 47 | + $status = match (true) { |
| 48 | + $e->getCode() >= 500 => ComponentStatusEnum::major_outage, |
| 49 | + default => ComponentStatusEnum::partial_outage, |
| 50 | + }; |
| 51 | + |
| 52 | + return new self( |
| 53 | + status: $status, |
| 54 | + successful: false, |
| 55 | + responseCode: $e->getCode() ?: null, |
| 56 | + error: $e->getMessage(), |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * The attributes used to persist this result as a component check. |
| 62 | + * |
| 63 | + * @return array<string, mixed> |
| 64 | + */ |
| 65 | + public function toCheckAttributes(): array |
| 66 | + { |
| 67 | + return [ |
| 68 | + 'status' => $this->status, |
| 69 | + 'successful' => $this->successful, |
| 70 | + 'response_code' => $this->responseCode, |
| 71 | + 'response_time' => $this->responseTime, |
| 72 | + ]; |
| 73 | + } |
| 74 | +} |
0 commit comments