cfmgrv4/app/Libraries/MySocket/Cloudflare/RecordSocket.php
2024-09-28 15:07:19 +09:00

146 lines
6.6 KiB
PHP

<?php
namespace App\Libraries\MySocket\Cloudflare;
use App\Models\Cloudflare\RecordModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\RecordEntity;
use App\Entities\Cloudflare\AuthEntity;
class RecordSocket extends CloudflareSocket
{
private $_model = null;
private $_zone_entity = null;
public function __construct(ZoneEntity $zone_entity)
{
$this->_zone_entity = $zone_entity;
$account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->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 getModel(): RecordModel
{
if ($this->_model === null) {
$this->_model = new RecordModel();
}
return $this->_model;
}
public function getArrayByResult($result, array $formDatas = []): array
{
$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'] = "on";
if (isset($result->locked) && $result->locked) {
$formDatas['locked'] = "off";
}
$formDatas['updated_at'] = date("Y-m-d H:i:s");
$formDatas['created_at'] = $result->created_on;
return $formDatas;
}
public function create(string $host, string $type, string $content, string $proxied): RecordEntity
{
//Socket용
//도메인생성을 위해 Cloudflare에 전송
$cf = $this->getClient()->post('zones/' . $this->_zone_entity->getPK() . '/dns_records', [
'name' => $host,
'type' => $type,
'content' => $content,
'proxied' => $proxied === 'on' ? true : false
]);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
$formDatas = $this->getArrayByResult($cf->result);
return $this->getModel()->create($formDatas);
}
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),
];
//변경작업: 2024-08-09
if (isset($formDatas['proxied']) && $formDatas['proxied'] === 'on') {
$datas['proxied'] = true;
$datas['ttl'] = 1;
} elseif (isset($formDatas['proxied']) && $formDatas['proxied'] === 'off') {
$datas['proxied'] = false;
$datas['ttl'] = 120;
}
$cf = $this->getClient()->put('zones/' . $this->_zone_entity->getPK() . '/dns_records', $datas);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function delete(RecordEntity $entity): void
{
$cf = $this->getClient()->delete('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK());
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
}
public function sync(RecordEntity $entity): void
{
//Sync형태
// $cf = $this->getClient()->get("zones/{$this->_zone_entity->getPK()}/dns_records/" . $entity->getPK());
// $cf = json_decode($cf->getBody());
// if (!$cf->success) {
// throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
// }
// return new RecordEntity($this->getArrayByResult($cf->result));
//Async형태
$promise = $this->getClient()->getAsync("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}");
$promise->then(
onFulfilled: function ($response) use ($entity): RecordEntity {
$record = json_decode($response->getBody(), true)['result'];
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();
}
//Reload
public function reload(): void
{
log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리 시작-----");
$entity_uids = [];
$results = $this->reload_procedure("zones/{$this->_zone_entity->getPK()}/dns_records");
foreach ($results as $result) {
$formDatas = $this->getArrayByResult($result);
$entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas);
$entity_uids[] = $entity->getPK();
}
//부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용
$this->getModel()->where(RecordModel::PARENT, $this->_zone_entity);
$this->getModel()->whereNotIn(RecordModel::PK, $entity_uids);
$this->getModel()->delete();
log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($results) . "개] 완료-----");
}
}