cfmgrv4/app/Services/Cloudflare/CloudflareService.php
2024-10-25 18:25:42 +09:00

103 lines
3.1 KiB
PHP

<?php
namespace App\Services\Cloudflare;
use App\Entities\Cloudflare\AuthEntity;
use App\Libraries\MySocket\CloudflareSocket;
use App\Models\Cloudflare\AuthModel;
use App\Services\CommonService;
use Psr\Http\Message\ResponseInterface;
abstract class CloudflareService extends CommonService
{
private $_mySockets = [];
private $_auth_entity = null;
private $_authModel = null;
protected function __construct()
{
parent::__construct();
$this->class_path = "Cloudflare/";
}
final public function getMySocket(): CloudflareSocket
{
if (!isset($this->_mySockets[$this->getAuthEntity()->getPK()])) {
$this->_mySockets[$this->getAuthEntity()->getPK()] = new CloudflareSocket($this->getAuthEntity());
}
return $this->_mySockets[$this->getAuthEntity()->getPK()];
}
final protected function getAuthEntity(): AuthEntity
{
if ($this->_auth_entity === null) {
throw new \Exception(__FUNCTION__ . "에서 인증정보가 없습니다.");
}
return $this->_auth_entity;
}
final protected function setAuthEntity(AuthEntity $auth_entity): void
{
$this->_auth_entity = $auth_entity;
}
final protected function getAuthModel(): AuthModel
{
if ($this->_authModel === null) {
$this->_authModel = new AuthModel();
}
return $this->_authModel;
}
private function reload_page(string $uri, int $page, int $per_page = 50): ResponseInterface
{
$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));
return $this->getMySocket()->get($uri, $query, $headers);
}
final protected function reload_procedure(string $uri): array
{
$page = 1; //1부터 시작
//한번에 가져올수 있는 갯수 (countfalre 5~50사이)
$response = $this->reload_page($uri, $page);
$body = json_decode($response->getBody());
// log_message("debug", var_export($body, true));
$per_page = $body->result_info->per_page;
$total_page = $body->result_info->total_pages;
$total_count = $body->result_info->total_count;
$results = [];
foreach ($body->result as $result) {
if (!is_object($result) || get_class($result) !== 'stdClass') {
log_message("error", "Cloudflare: result is not a stdClass:\n" . var_export($body, true) . "\n");
} else {
array_push($results, $result);
}
}
for ($i = $page + 1; $i <= $total_page; $i++) {
// API 제한을 고려한 지연 추가
// usleep(100000); // 0.1초 대기
$response = $this->reload_page($uri, $i, $per_page);
$body = json_decode($response->getBody());
foreach ($body->result as $result) {
if (!is_object($result) || get_class($result) !== 'stdClass') {
log_message("error", "Cloudflare: result is not a stdClass:\n" . var_export($body, true) . "\n");
} else {
array_push($results, $result);
}
}
log_message("notice", sprintf(
"현재: page[%s/%s] , total_count:[%s] , results:[%s]",
$i,
$total_page,
$total_count,
count($results)
));
}
return $results;
}
}