cfmgrv4/app/Libraries/MySocket/CloudflareSocket.php
2024-10-05 11:51:52 +09:00

87 lines
2.7 KiB
PHP

<?php
namespace App\Libraries\MySocket;
use Psr\Http\Message\ResponseInterface;
use App\Models\Cloudflare\AuthModel;
use App\Models\Cloudflare\AccountModel;
use App\Entities\Cloudflare\AuthEntity;
abstract class CloudflareSocket extends MySocket
{
private static int $_request = 0;
private static int $_request_max = 1000;
private static int $_request_perpage_max = 700;
private static int $_request_timewait = 60;
private $_authModel = null;
private $_accountModel = null;
private $_auth_entity = null;
protected function __construct(AuthEntity $auth_entity)
{
parent::__construct([
'base_uri' => 'https://api.cloudflare.com/client/v4/',
'headers' => [
'X-Auth-Email' => $this->_auth_entity->getID(), // 인증 토큰 사용
'X-Auth-Key' => $this->_auth_entity->getAuthKey(), // 인증 토큰 사용
'Content-Type' => 'application/json',
]
]);
$this->_auth_entity = $auth_entity;
self::$_request_max = getenv("cfmgr.request.max") ?: 1000;
self::$_request_perpage_max = getenv("cfmgr.request.perpage.max") ?: 700;
self::$_request_timewait = getenv("cfmgr.request.timewait") ?: 60;
}
abstract protected function getArrayByResult($result, array $formDatas = []): array;
final public function request(string $method, $uri = '', array $options = []): ResponseInterface
{
if (self::$_request >= self::$_request_max) {
log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait));
sleep(intval(self::$_request_timewait));
self::$_request = 0;
log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait));
}
self::$_request++;
return parent::request($method, $uri, $options);
}
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;
}
final protected function reload_procedure($uri): array
{
$page = 1; //1부터 시작
$results = [];
do {
$query = [
'page' => $page,
'per_page' => self::$_request_perpage_max,
'match' => 'all',
];
$response = $this->getClient()->get($uri, $query);
$cf = json_decode($response->getBody());
if (!$cf->success) {
$message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
log_message("error", $message);
throw new \Exception($message);
}
$results = array_merge($results, $cf->result);
if (count($cf->result) < self::$_request_perpage_max) {
break;
}
$page++;
} while (true);
return $results;
}
}