90 lines
2.9 KiB
PHP
90 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Imports;
|
|
|
|
use App\Models\Artist;
|
|
use App\Enums\ArtistCategory;
|
|
use App\Helpers\ChineseNameConverter;
|
|
use App\Helpers\ChineseStrokesConverter;
|
|
use Illuminate\Support\Collection;
|
|
use Maatwebsite\Excel\Concerns\ToCollection;
|
|
use Maatwebsite\Excel\Concerns\WithHeadingRow;
|
|
use Maatwebsite\Excel\Concerns\WithChunkReading;
|
|
use Maatwebsite\Excel\Concerns\WithBatchInserts;
|
|
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
|
|
|
|
class ArtistDataImport implements ToCollection, WithHeadingRow, WithChunkReading, WithBatchInserts
|
|
{
|
|
|
|
public function __construct()
|
|
{
|
|
// 關閉 heading row 格式化
|
|
HeadingRowFormatter::default('none');
|
|
}
|
|
public function collection(Collection $rows)
|
|
{
|
|
// 建立現有歌手名稱的查找表,避免重複建立
|
|
static $existingNames = null;
|
|
|
|
if ($existingNames === null) {
|
|
$existingNames = array_flip(array_map('trim', Artist::pluck('name')->all()));
|
|
}
|
|
|
|
$toInsert = [];
|
|
|
|
foreach ($rows as $row) {
|
|
$name=trim($row['歌手姓名'] ?? '');
|
|
if (empty($name)) continue;
|
|
|
|
// 若資料庫已有該名稱,跳過
|
|
if (isset($existingNames[$name])) continue;
|
|
|
|
// 字元處理
|
|
$simplified = ChineseNameConverter::convertToSimplified($name);
|
|
if (!$row->has('歌手注音')) {
|
|
$phoneticAbbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);
|
|
} else {
|
|
$phoneticAbbr = trim($row['歌手注音']);
|
|
}
|
|
$pinyinAbbr = ChineseNameConverter::getKTVPinyinAbbr($simplified);
|
|
if (!$row->has('歌手筆畫')) {
|
|
$chars = preg_split('//u', $name, -1, PREG_SPLIT_NO_EMPTY);
|
|
$firstChar = $chars[0] ?? null;
|
|
$strokesAbbr = $firstChar ? ChineseStrokesConverter::getStrokes($firstChar) : null;
|
|
} else {
|
|
$strokesAbbr = trim($row['歌手筆畫']);
|
|
}
|
|
// 準備 song 資料
|
|
$now = now();
|
|
$toInsert[] = [
|
|
'name' => $name,
|
|
'category' => ArtistCategory::tryFrom(trim($row['歌手分類'] ?? '未定義')) ?? ArtistCategory::Unset,
|
|
'simplified' => $simplified,
|
|
'phonetic_abbr' => $phoneticAbbr,
|
|
'pinyin_abbr' => $pinyinAbbr,
|
|
'strokes_abbr' => $strokesAbbr,
|
|
'enable' =>trim($row['狀態'] ?? 1),
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
];
|
|
|
|
// 新增到快取,避免後面重複匯入
|
|
$existingNames[$name] = true;
|
|
}
|
|
Artist::insert($toInsert);
|
|
}
|
|
|
|
public function chunkSize(): int
|
|
{
|
|
return 100;
|
|
}
|
|
public function batchSize(): int
|
|
{
|
|
return 100;
|
|
}
|
|
|
|
public function headingRow(): int
|
|
{
|
|
return 1;
|
|
}
|
|
} |