在我的数据库中,我有通知表,其中包含要检查的URL并检查频率列和警报频率列。我现在尝试做的是代码。发送http请求后,代码应该能够执行以下操作。
这就是我想要实现但未能做到的事情。我的代码需要一些改进。
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
use Carbon;
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client();
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
$this->default_alert_frequency = Setting::defaultAlertFrequency();
}
private function addStatusToNotification(Notification $notification, Status $status, $resCode)
{
$notification->statuses()->attach($status, [
'values' => $resCode === 200
? 'up'
: 'down'
]);
}
private function report(Notification $notification, $resCode)
{
/* how to send slack to different slach channels, now it is sending only to one channel!*/
$this->reporter->slack($notification->website_url . ':' . ' is down' . ' this is the status code!' . ' @- ' .$resCode,
$notification->slack_channel);
$this->reporter->mail($notification->email,$notification->website_url.' is down '. ' this is the status Code: '. $resCode);
}
private function sendNotification(Notification $notification, Status $status, $status_health, $frequency, $resCode)
{
$elapsed_time = \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();
if ($elapsed_time >= $frequency) {
$this->addStatusToNotification($notification, $status, $resCode);
if ($resCode != 200) {
$this->report($notification, $resCode);
}
}
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$this->updateStatus($notification, $status);
}
}
private function updateStatus(Notification $notification, Status $status)
{
$resCode = $this->getStatusCode($notification->website_url);
$this->sendNotification(
$notification,
$status,
$notification->status('health'),
$this->getFrequency($notification, $resCode),
$resCode
);
}
private function getFrequency(Notification $notification, $resCode)
{
switch ( $resCode) {
case '200':
return isset($notification->check_frequency)
? intval($notification->check_frequency)
: $this->default_check_frequency;
break;
default:
return isset($notification->alert_frequency)
? intval($notification->alert_frequency)
: $this->default_alert_frequency;
break;
}
}
private function getStatusCode($url)
{
try {
$response = $this->client->get($url, [
'http_errors' => false
]);
return $response->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
}
}
}
你能帮忙解决这个问题。我的代码中遗漏了一些东西?