cfmgrv4/app/Libraries/Cloudflare/Cloudflare.php
2024-10-12 09:42:17 +09:00

93 lines
2.8 KiB
PHP

<?php
namespace App\Libraries\Cloudflare;
use App\Models\Cloudflare\AuthModel;
use App\Models\Cloudflare\AccountModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Libraries\CommonLibrary;
use App\Entities\Cloudflare\AuthEntity;
abstract class Cloudflare extends CommonLibrary
{
private $_auth_entity = null;
private $_authModel = null;
private $_accountModel = null;
protected function __construct(AuthEntity $auth_entity)
{
$this->_auth_entity = $auth_entity;
parent::__construct();
}
abstract protected function getArrayByResult($result, array $formDatas = []): array;
final public function getMySocket(): CloudflareSocket
{
if ($this->_mySocket === null) {
$this->_mySocket = new CloudflareSocket($this->getAuthEntity());
}
return $this->_mySocket;
}
final protected function getAuthEntity(): AuthEntity
{
if ($this->_auth_entity === null) {
throw new \Exception(__FUNCTION__ . "에서 인증정보가 없습니다.");
}
return $this->_auth_entity;
}
final protected function getAuthModel(): AuthModel
{
if ($this->_authModel === null) {
$this->_authModel = new AuthModel();
}
return $this->_authModel;
}
final protected function getAccountModel(): AccountModel
{
if ($this->_accountModel === null) {
$this->_accountModel = new AccountModel();
}
return $this->_accountModel;
}
private function reload_page(string $uri, int $page, int $per_page = 50): mixed
{
$query = [
'page' => $page,
'per_page' => $per_page,
'match' => 'all',
'cache_buster' => uniqid(), // 매 요청마다 고유한 값 사용
];
// 요청 헤더에 캐시 제어 추가
$headers = [
'Cache-Control' => 'no-cache',
'Pragma' => 'no-cache',
];
// log_message("debug", var_export($query, true));
$response = $this->getMySocket()->get($uri, $query, $headers);
$cf = json_decode($response->getBody());
if (!$cf->success) {
$message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
log_message("error", $message);
throw new \Exception($message);
}
// log_message("debug", "Page {$page} response: " . var_export($cf->result_info, true));
return $cf;
}
final protected function reload_procedure(string $uri): array
{
$page = 1; //1부터 시작
//한번에 가져올수 있는 갯수 (countfalre 5~50사이)
$cf = $this->reload_page($uri, $page);
$per_page = $cf->result_info->per_page;
$total_page = $cf->result_info->total_pages;
$results = $cf->result;
for ($i = $page + 1; $i <= $total_page; $i++) {
// API 제한을 고려한 지연 추가
usleep(100000); // 0.1초 대기
$cf = $this->reload_page($uri, $i, $per_page);
$results = array_merge($results, $cf->result);
log_message("notice", "현재: page[{$i}/{$total_page}] , result수[" . count($results) . "]");
}
return $results;
}
}