KTV/app/Imports/ArtistDataImport.php

74 lines
2.4 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)
{
$toInsert = [];
foreach ($rows as $row) {
$name=trim($row['歌手姓名'] ?? '');
if (empty($name)) continue;
// 字元處理
$simplified = ChineseNameConverter::convertToSimplified($name);
if (!array_key_exists('歌手注音', $row)) {
$phoneticAbbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);
} else {
$phoneticAbbr = trim($row['歌手注音']);
}
$pinyinAbbr = ChineseNameConverter::getKTVPinyinAbbr($simplified);
if (!array_key_exists('歌手注音', $row)) {
$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 資料
$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)
];
}
Artist::insert($toInsert);
}
public function chunkSize(): int
{
return 100;
}
public function batchSize(): int
{
return 100;
}
public function headingRow(): int
{
return 1;
}
}