LAR_Maintenance/app/Services/ZabbixService.php

113 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2024-08-16 16:20:45 +00:00
<?php
namespace App\Services;
2024-08-16 21:37:42 +00:00
use Carbon\Carbon;
2024-08-16 16:20:45 +00:00
use Exception;
use Illuminate\Support\Facades\Http;
class ZabbixService
{
public string $token = "";
public string $url = "";
public int $id = 1;
2024-08-16 21:37:42 +00:00
function __construct($url)
{
2024-08-16 16:20:45 +00:00
$this->url = $url;
}
2024-08-16 21:37:42 +00:00
public function connect($username, $password)
2024-08-16 16:20:45 +00:00
{
2024-08-16 21:37:42 +00:00
$this->token = $this->request([
2024-08-16 16:20:45 +00:00
"jsonrpc" => "2.0",
"method" => "user.login",
"params" => [
2024-08-16 21:37:42 +00:00
"username" => $username,
"password" => $password,
2024-08-16 16:20:45 +00:00
],
"id" => $this->id,
"auth" => null,
]);
2024-08-16 21:37:42 +00:00
return $this->token;
2024-08-16 16:20:45 +00:00
}
public function hosts($params = [])
{
2024-08-16 21:37:42 +00:00
return $this->request([
2024-08-16 16:20:45 +00:00
"jsonrpc" => "2.0",
"method" => "host.get",
"params" => $params,
"id" => $this->id,
"auth" => $this->token,
]);
}
public function hostGroups($params = [])
{
2024-08-16 21:37:42 +00:00
return $this->request([
2024-08-16 16:20:45 +00:00
"jsonrpc" => "2.0",
"method" => "hostgroup.get",
"params" => $params,
"id" => $this->id,
"auth" => $this->token,
]);
}
2024-08-16 21:37:42 +00:00
public function maintenances($params = [])
{
return $this->request([
2024-08-16 16:20:45 +00:00
"jsonrpc" => "2.0",
"method" => "maintenance.get",
"params" => $params,
"id" => $this->id,
"auth" => $this->token,
]);
}
2024-08-16 21:37:42 +00:00
public function maintenancesCreate($params = [])
{
return $this->request([
"jsonrpc" => "2.0",
"method" => "maintenance.create",
"params" => $params,
"id" => $this->id,
"auth" => $this->token,
]);
}
public function maintenancesUpdate( $params = [])
{
return $this->request([
"jsonrpc" => "2.0",
"method" => "maintenance.update",
"params" => $params,
"id" => $this->id,
"auth" => $this->token,
]);
}
2024-08-16 16:20:45 +00:00
/*Helpers*/
2024-08-16 21:37:42 +00:00
private function request($body = [])
{
if (empty($this->token) && $body['auth'] != null) {
2024-08-16 16:20:45 +00:00
throw new Exception("you need to connect first", 1);
}
$response = Http::withoutVerifying()->post($this->url . "/api_jsonrpc.php", $body);
if (!$response->successful()) {
throw new Exception("Unable To Request", 1);
}
$responseObject = $response->json();
if (isset($responseObject['error'])) {
throw new Exception($responseObject['error']['data'], $responseObject['error']['code']);
}
$this->id++;
2024-08-16 21:37:42 +00:00
return is_array($responseObject["result"]) ? collect($responseObject["result"]) : $responseObject["result"];
2024-08-16 16:20:45 +00:00
}
}