cfmgrv4/app/Services/Cloudflare/Cloudflare.php
2024-10-21 09:32:49 +09:00

85 lines
2.6 KiB
PHP

<?php
namespace App\Services\Cloudflare;
use App\Models\Cloudflare\AuthModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Entities\Cloudflare\AuthEntity;
use Psr\Http\Message\ResponseInterface;
abstract class Cloudflare
{
private $_mySocket = null;
private $_auth_entity = null;
private $_authModel = null;
protected function __construct(AuthEntity $auth_entity)
{
$this->_auth_entity = $auth_entity;
}
abstract protected function getArrayByResult(\stdClass $result, array $formDatas = []): array;
abstract protected function getParentEntity(): mixed;
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;
}
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;
$results = [$body->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($result, true) . "\n");
} else {
array_push($results, $body->result);
}
}
log_message("notice", "현재: page[{$i}/{$total_page}] , result수[" . count($results) . "]");
}
return $results;
}
}