dyndns/app/Jobs/Updater/Cloudflare.php

98 lines
2.9 KiB
PHP
Raw Permalink Normal View History

2019-08-10 14:34:53 +00:00
<?php
namespace App\Jobs\Updater;
use App\Jobs\Job;
use App\Jobs\Updater\IUpdater;
use GuzzleHttp\Client;
class Cloudflare extends Job implements IUpdater
{
private $domain;
private $ip;
/**
* Create a new job instance.
*
* @return void
*/
public function config($domain, $ip)
{
$this->domain = $domain;
$this->ip = $ip;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Client $client)
{
//Get Zone for Domain in config
$res = $client->get("https://api.cloudflare.com/client/v4/zones", [
"query" => [
"name" => getenv("CLOUDFLARE_DOMAIN")
],
"headers" => [
"X-Auth-Email" => getenv("CLOUDFLARE_MAIL"),
"X-Auth-Key" => getenv("CLOUDFLARE_API_KEY")
]
]);
$zoneData = \GuzzleHttp\json_decode((string)$res->getBody(), true);
if (count($zoneData["result"]) != 1) {
throw new \Exception("No or more than once Zone found");
}
//Check if record exists
$res = $client->get("https://api.cloudflare.com/client/v4/zones/".$zoneData["result"][0]["id"]."/dns_records", [
"query" => [
"name" => $this->domain,
"type" => "A",
],
"headers" => [
"X-Auth-Email" => getenv("CLOUDFLARE_MAIL"),
"X-Auth-Key" => getenv("CLOUDFLARE_API_KEY")
]
]);
$recordData = \GuzzleHttp\json_decode((string)$res->getBody(), true);
if (count($recordData["result"]) > 1) {
throw new \Exception("More than once Record found");
}
//Update or Create Record
if (count($recordData["result"]) == 0) {
$res = $client->post("https://api.cloudflare.com/client/v4/zones/".$zoneData["result"][0]["id"]."/dns_records", [
"json" => [
"name" => $this->domain,
"type" => "A",
"content"=> $this->ip,
"ttl" => 120
],
"headers" => [
"X-Auth-Email" => getenv("CLOUDFLARE_MAIL"),
"X-Auth-Key" => getenv("CLOUDFLARE_API_KEY")
]
]);
} else {
$res = $client->put("https://api.cloudflare.com/client/v4/zones/".$zoneData["result"][0]["id"]."/dns_records/".$recordData["result"][0]["id"], [
"json" => [
"name" => $this->domain,
"type" => "A",
"content"=> $this->ip,
"ttl" => 120
],
"headers" => [
"X-Auth-Email" => getenv("CLOUDFLARE_MAIL"),
"X-Auth-Key" => getenv("CLOUDFLARE_API_KEY")
]
]);
}
}
}