Files
2026-09-15 10:35:56 +08:00

98 lines
4.0 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\LingxingErp\Model\Sku;
use Esun\LingxingErp\Model\Api\ApiException;
use Esun\LingxingErp\Model\Api\Client;
use Esun\LingxingErp\Model\Api\Endpoint;
use Esun\LingxingErp\Model\Sync\LogWriter;
class PairFetcher
{
/**
* Lingxing API documentation:
* https://apidoc.lingxing.com/#/docs/MultiPlatform/V2/PairListV2
*/
private const MAX_PAGES = 10000;
private const MSKU_BATCH_SIZE = 200;
public function __construct(
private readonly Client $client,
private readonly LogWriter $logWriter
) {
}
/** @param string[] $mskus @return array<int, array<string, mixed>> */
public function fetchAll(int $platformCode, string $storeId, array $mskus, int $pageSize): array
{
$pairs = [];
foreach (array_chunk(array_values(array_unique($mskus)), self::MSKU_BATCH_SIZE) as $mskuBatch) {
$offset = 0;
for ($page = 1; $page <= self::MAX_PAGES; $page++) {
$request = [
'offset' => $offset,
'length' => $pageSize,
'msku' => $mskuBatch,
'platform_codes' => [(string)$platformCode],
'store_ids' => [$storeId],
];
$started = microtime(true);
$response = [];
try {
$response = $this->client->post(Endpoint::PAIR_LIST, $request);
$rows = $response['data']['list'] ?? null;
if (!is_array($rows)) {
throw new \RuntimeException('Lingxing PairListV2 response is missing data.list.');
}
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_pair_lookup',
'entity_type' => 'product',
'external_id' => $storeId,
'status' => 'success',
'attempt_number' => 1,
'request_id' => (string)($response['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $response,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
} catch (\Throwable $exception) {
$apiResponse = $exception instanceof ApiException ? $exception->getResponse() : $response;
$this->logWriter->write([
'direction' => 'pull',
'operation' => 'sku_pair_lookup',
'entity_type' => 'product',
'external_id' => $storeId,
'status' => 'failed',
'attempt_number' => 1,
'error_code' => $exception instanceof ApiException
? $exception->getErrorCode()
: (string)$exception->getCode(),
'error_message' => $exception->getMessage(),
'request_id' => (string)($apiResponse['request_id'] ?? ''),
'request_payload' => $request,
'response_payload' => $apiResponse,
'duration_ms' => (int)round((microtime(true) - $started) * 1000),
]);
throw $exception;
}
foreach ($rows as $row) {
if (is_array($row)) {
$pairs[] = $row;
}
}
$count = count($rows);
if ($count < $pageSize) {
break;
}
$offset += $count;
if ($page === self::MAX_PAGES) {
throw new \RuntimeException('Lingxing PairListV2 exceeded the maximum pagination limit.');
}
}
}
return $pairs;
}
}