urlsnail/app/Jobs/ImportBookmark.php

62 lines
1.7 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\Bookmark;
use App\Models\BookmarkTag;
use App\Models\Tag;
use DateTimeImmutable;
use DateTimeInterface;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ImportBookmark implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected array $bookmarks_json;
/**
* Create a new job instance.
*/
public function __construct(array ...$bookmarks_json)
{
$this->bookmarks_json = $bookmarks_json;
}
/**
* Execute the job.
*/
public function handle(): void
{
foreach ($this->bookmarks_json as $bookmark_json) {
$created_at = DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601_EXPANDED, $bookmark_json['time']);
$bookmark = new Bookmark;
$bookmark->href = $bookmark_json['href'];
$bookmark->title = $bookmark_json['description'];
$bookmark->description = $bookmark_json['extended'];
$bookmark->created_at = $created_at;
$bookmark->updated_at = $created_at;
$bookmark->save();
$tokens = explode(' ', $bookmark_json['tags']);
foreach ($tokens as $tag_raw) {
$tag = Tag::firstOrCreate(
[
'name' => $tag_raw,
]
);
$bookmark_tag = new BookmarkTag;
$bookmark_tag->bookmark_id = $bookmark->id;
$bookmark_tag->tag_id = $tag->id;
$bookmark_tag->save();
}
}
}
}