Skip to content

Instantly share code, notes, and snippets.

@shibafu528
Created October 5, 2025 12:12
Show Gist options
  • Select an option

  • Save shibafu528/455ea02e73417e9c7d9abffa61f9a593 to your computer and use it in GitHub Desktop.

Select an option

Save shibafu528/455ea02e73417e9c7d9abffa61f9a593 to your computer and use it in GitHub Desktop.
for tissue dev
<?php
declare(strict_types=1);
use App\Exceptions\CsvImportException;
use App\Tag;
use Illuminate\Support\Facades\DB;
use League\Csv\Reader;
// target user id
const OWNER_USER_ID = 128;
function parseTags(int $line, array $record): array
{
$tags = [];
foreach (array_keys($record) as $column) {
if (preg_match('/\Aタグ\d{1,2}\z/u', $column) !== 1) {
continue;
}
$tag = trim($record[$column] ?? '');
if (empty($tag)) {
continue;
}
if (mb_strlen($tag) > 255) {
throw new CsvImportException("{$line} 行 : {$column}は255文字以内にしてください。");
}
if (strpos($tag, "\n") !== false) {
throw new CsvImportException("{$line} 行 : {$column}に改行を含めることはできません。");
}
if (strpos($tag, ' ') !== false) {
throw new CsvImportException("{$line} 行 : {$column}にスペースを含めることはできません。");
}
$tags[] = Tag::firstOrCreate(['name' => $tag]);
if (count($tags) >= 40) {
break;
}
}
return $tags;
}
$user = \App\User::find(OWNER_USER_ID);
$in = file_get_contents('php://stdin');
$csv = Reader::createFromString($in);
$csv->setHeaderOffset(0);
DB::transaction(function () use ($user, $csv) {
$collection = $user->collections()->create([
'title' => 'import ' . date('Y-m-d H:i:s'),
]);
foreach ($csv->getRecords() as $line => $row) {
$ci = $collection->items()->create([
'link' => $row['オカズリンク'],
]);
$tags = parseTags($line, $row);
if (!empty($tags)) {
$ci->tags()->sync($tags);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment