2022-08-17 09:39:53 -04:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\References;
|
|
|
|
|
|
|
|
use BookStack\Entities\Models\Page;
|
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
|
|
2022-08-20 07:07:38 -04:00
|
|
|
class ReferenceStore
|
2022-08-17 09:39:53 -04:00
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Update the outgoing references for the given page.
|
|
|
|
*/
|
|
|
|
public function updateForPage(Page $page): void
|
|
|
|
{
|
|
|
|
$this->updateForPages([$page]);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update the outgoing references for all pages in the system.
|
|
|
|
*/
|
|
|
|
public function updateForAllPages(): void
|
|
|
|
{
|
|
|
|
Reference::query()
|
|
|
|
->where('from_type', '=', (new Page())->getMorphClass())
|
2022-08-17 11:59:23 -04:00
|
|
|
->delete();
|
2022-08-17 09:39:53 -04:00
|
|
|
|
2022-08-29 12:46:41 -04:00
|
|
|
Page::query()->select(['id', 'html'])->chunk(100, function (Collection $pages) {
|
2022-08-17 09:39:53 -04:00
|
|
|
$this->updateForPages($pages->all());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update the outgoing references for the pages in the given array.
|
|
|
|
*
|
|
|
|
* @param Page[] $pages
|
|
|
|
*/
|
|
|
|
protected function updateForPages(array $pages): void
|
|
|
|
{
|
|
|
|
if (count($pages) === 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$parser = CrossLinkParser::createWithEntityResolvers();
|
|
|
|
$references = [];
|
|
|
|
|
2022-08-29 12:46:41 -04:00
|
|
|
$pageIds = array_map(fn (Page $page) => $page->id, $pages);
|
2022-08-17 09:39:53 -04:00
|
|
|
Reference::query()
|
|
|
|
->where('from_type', '=', $pages[0]->getMorphClass())
|
|
|
|
->whereIn('from_id', $pageIds)
|
|
|
|
->delete();
|
|
|
|
|
|
|
|
foreach ($pages as $page) {
|
|
|
|
$models = $parser->extractLinkedModels($page->html);
|
|
|
|
|
|
|
|
foreach ($models as $model) {
|
|
|
|
$references[] = [
|
2022-08-29 12:46:41 -04:00
|
|
|
'from_id' => $page->id,
|
2022-08-17 09:39:53 -04:00
|
|
|
'from_type' => $page->getMorphClass(),
|
2022-08-29 12:46:41 -04:00
|
|
|
'to_id' => $model->id,
|
|
|
|
'to_type' => $model->getMorphClass(),
|
2022-08-17 09:39:53 -04:00
|
|
|
];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach (array_chunk($references, 1000) as $referenceDataChunk) {
|
|
|
|
Reference::query()->insert($referenceDataChunk);
|
|
|
|
}
|
|
|
|
}
|
2022-08-29 12:46:41 -04:00
|
|
|
}
|