cfmgrv4/app/Services/Cloudflare/Record.php
2024-10-21 09:26:05 +09:00

171 lines
7.7 KiB
PHP

<?php
namespace App\Services\Cloudflare;
use App\Entities\Cloudflare\RecordEntity;
use App\Entities\Cloudflare\ZoneEntity;
use App\Models\Cloudflare\AccountModel;
use App\Models\Cloudflare\RecordModel;
class Record extends Cloudflare
{
private ?ZoneEntity $_parent_entity = null;
private ?RecordModel $_model = null;
private ?AccountModel $_accountModel = null;
public function __construct(ZoneEntity $zone_entity)
{
$this->_parent_entity = $zone_entity;
$account_entity = $this->getAccountModel()->getEntityByPK($this->getParentEntity()->getParent());
if ($account_entity === null) {
throw new \Exception("해당 계정정보를 찾을수 없습니다.");
}
$auth_entity = $this->getAuthModel()->getEntityByPK($account_entity->getParent());
if ($auth_entity === null) {
throw new \Exception("해당 계정정보를 찾을수 없습니다.");
}
parent::__construct($auth_entity);
}
protected function getParentEntity(): ZoneEntity
{
if ($this->_parent_entity === null) {
throw new \Exception(__FUNCTION__ . "에서 부모정보가 없습니다.");
}
return $this->_parent_entity;
}
protected function getModel(): RecordModel
{
if ($this->_model === null) {
$this->_model = new RecordModel();
}
return $this->_model;
}
protected function getAccountModel(): AccountModel
{
if ($this->_accountModel === null) {
$this->_accountModel = new AccountModel();
}
return $this->_accountModel;
}
protected function getArrayByResult(\stdClass $result, array $formDatas = []): array
{
// log_message("debug", var_export($result, true));
$formDatas[RecordModel::PK] = $result->id;
$formDatas[RecordModel::PARENT] = $result->zone_id;
$formDatas[RecordModel::TITLE] = $result->name;
$formDatas['type'] = $result->type;
$formDatas['content'] = $result->content;
$formDatas['ttl'] = (int) $result->ttl;
$formDatas['proxiable'] = $result->proxiable ? "on" : "off";
$formDatas['proxied'] = $result->proxied ? "on" : "off";
$formDatas['locked'] = isset($result->locked) && $result->locked ? "off" : "on";
$formDatas['updated_at'] = date("Y-m-d H:i:s");
$formDatas['created_at'] = $result->created_on;
// log_message("debug", print_r($formDatas, true));
return $formDatas;
}
public function create(string $host, string $type, string $content, string $proxied): RecordEntity
{
//Socket용
//호스트생성을 위해 Cloudflare에 전송
$datas = [
'name' => $host,
'type' => $type,
'content' => $content,
'proxied' => $proxied === 'on' ? true : false
];
$response = $this->getMySocket()->post("zones/{$this->getParentEntity()->getPK()}/dns_records", $datas);
$body = json_decode($response->getBody());
//DB생성
return $this->getModel()->create($this->getArrayByResult($body->result));
}
public function modify(RecordEntity $entity, array $formDatas): RecordEntity
{
//TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용
$datas = [
'type' => isset($formDatas['type']) ? $formDatas['type'] : $entity->type,
'name' => isset($formDatas['host']) ? $formDatas['host'] : $entity->host,
'content' => isset($formDatas['content']) ? $formDatas['content'] : $entity->content,
'proxied' => $entity->proxied == 'on' ? true : false,
'ttl' => intval($entity->ttl),
];
if (isset($formDatas['proxied'])) {
if ($formDatas['proxied'] === 'on') {
$datas['proxied'] = true;
$datas['ttl'] = 1;
} else {
$datas['proxied'] = false;
$datas['ttl'] = 120;
}
}
// 인코딩된 JSON을 확인
// throw new \Exception("Record:" . __FUNCTION__ . "\n" . json_encode($datas, JSON_PRETTY_PRINT) . "\n" . var_export($datas, true));
$response = $this->getMySocket()->put("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}", $datas);
$body = json_decode($response->getBody());
// DB 수정
return $this->getModel()->modify($entity, $this->getArrayByResult($body->result));
}
public function delete(RecordEntity $entity): RecordEntity
{
$this->getMySocket()->delete("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}");
//DB삭제
$this->getModel()->delete($entity->getPK());
log_message("debug", $this->getModel()->getLastQuery());
return $entity;
}
public function sync(RecordEntity $entity): RecordEntity
{
// 기존 Sync형태
$response = $this->getMySocket()->get("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}");
$body = json_decode($response->getBody());
// DB수정
// log_message("debug", var_export($cf->result, true));
$entity = $this->getModel()->modify($entity, $this->getArrayByResult($body->result));
//Async형태
// $promise = $this->getMySocket()getAsync("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}");
// $entity =$promise->then(
// onFulfilled: function ($response) use ($entity): RecordEntity {
// $record = json_decode($response->getBody(), true)['result'];
// log_message("debug", var_export($record));
// //DB수정
// return $this->getModel()->modify($entity, $this->getArrayByResult($record));
// },
// onRejected: function ($error) {
// log_message('error', 'Failed to fetch DNS records: ' . $error->getMessage());
// throw new \Exception('Failed to fetch DNS records: ' . $error->getMessage());
// }
// );
// $promise->wait();
return $entity;
}
//Reload
public function reload(): array
{
log_message("notice", "\n-----------Zone {$this->getParentEntity()->getTitle()}의 Record 처리 시작-----------");
$entitys = [];
try {
$results_array = $this->reload_procedure("zones/{$this->getParentEntity()->getPK()}/dns_records");
if (count(value: $results_array) > 0) {
foreach ($results_array as $results) {
foreach ($results as $result) {
if (!is_object($result) || get_class($result) !== 'stdClass') {
throw new \Exception("Record: result is not a stdClass:\n" . var_export($result, true) . "\n");
}
$formDatas = $this->getArrayByResult($result);
$entitys[$formDatas[RecordModel::PK]] = $this->getModel()->modify(new RecordEntity(), $formDatas);
}
}
//부모키를 기준으로 CF에 존재하지 않는 데이터 DB삭제
$this->getModel()->where(RecordModel::PARENT, $this->getParentEntity()->getPK());
$this->getModel()->whereNotIn(RecordModel::PK, array_keys($entitys));
$this->getModel()->delete();
log_message("debug", $this->getModel()->getLastQuery());
}
} catch (\Exception $e) {
log_message("error", $e->getMessage());
throw new \Exception($e->getMessage());
}
log_message("notice", "\n-----------Zone {$this->getParentEntity()->getTitle()}의 Record처리[" . count($entitys) . "개] 완료-----------");
return $entitys;
}
}