Files
datahub/backend/app/Platform/Tmall/TmallOrderParser.php
T
2025-12-01 11:12:33 +08:00

119 lines
3.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Platform\Tmall;
use App\Model\Company;
use App\Model\Model as Entity;
use App\Model\Store;
use App\Entity\Parse\EntityParse;
use Hyperf\Collection\LazyCollection;
use InvalidArgumentException;
/**
* 天猫订单解析器示例
*
* 展示如何继承 EntityParse 实现自定义解析逻辑
*/
class TmallOrderParser extends EntityParse
{
/**
* 公司作用域匹配
*
* 从 metadata 中提取 company_id,然后查询数据库获取公司对象
*
* @param array $metadata
* @return Company
* @throws InvalidArgumentException
*/
public function companyScopeMatch(array $metadata): Company
{
// 验证必需字段
if (!isset($metadata['company_id'])) {
throw new InvalidArgumentException('company_id is required in metadata');
}
$companyId = $metadata['company_id'];
$company = Company::find($companyId);
if (!$company) {
throw new InvalidArgumentException("Company with ID {$companyId} not found");
}
return $company;
}
/**
* 店铺作用域匹配
*
* 从 metadata 中提取 store_id,然后查询数据库获取店铺对象
*
* @param array $metadata
* @return Store
* @throws InvalidArgumentException
*/
public function storeScopeMatch(array $metadata): Store
{
// 验证必需字段
if (!isset($metadata['store_id'])) {
throw new InvalidArgumentException('store_id is required in metadata');
}
$storeId = $metadata['store_id'];
$store = Store::find($storeId);
if (!$store) {
throw new InvalidArgumentException("Store with ID {$storeId} not found");
}
return $store;
}
/**
* 实体数据映射
*
* 将原始数据映射为可供 Model 使用的数组集合
*
* @param array $rawData 原始数据数组,通常来自 $data['raw_data']
* @return LazyCollection 返回 LazyCollection,每个元素为可供 Model::fill() 使用的数组
*/
public function entityMap(array $rawData): LazyCollection
{
// 使用 LazyCollection 进行延迟处理,提高性能
return LazyCollection::make(function () use ($rawData) {
// 如果 rawData 是单个记录,转换为数组
$records = isset($rawData[0]) ? $rawData : [$rawData];
foreach ($records as $record) {
// 映射每条原始数据到 Model 可用的数组格式
yield [
'platform_id' => $this->getPlatform()->id,
'company_id' => $this->getCompany()->id,
'store_id' => $this->getStore()->id,
'unique_id' => $record['unique_id'] ?? $this->getData()['unique_id'] ?? null,
'raw_data' => json_encode($record),
// 根据实际业务需求映射其他字段
// 例如:
// 'order_id' => $record['order_id'] ?? null,
// 'order_status' => $record['order_status'] ?? null,
// 'order_amount' => $record['order_amount'] ?? 0,
// ...
];
}
});
}
/**
* 可选:覆盖唯一标识符提取逻辑
*
* 如果使用默认的 unique_id 提取逻辑,则无需覆盖此方法
*/
// public function entityUniqueIdentifierExtract(array $metadata): string|int
// {
// return $metadata['custom_id_field'] ?? throw new InvalidArgumentException('custom_id_field not found');
// }
}